PJax not working with MVC project - pjax

I've followed the samples. I added a _PjaxLayout:
<title>#ViewBag.Title</title>
#RenderBody()
Modified my _Layout:
<div id="shell">
#RenderBody()
</div>
<script type="text/javascript">
$(function () {
// pjax
$.pjax.defaults.timeout = 5000;
$('a').pjax('#shell');
})
</script>
Updated ViewStart:
#{
if (Request.Headers["X-PJAX"] != null) {
Layout = "~/Views/Shared/_PjaxLayout.cshtml";
} else {
Layout = "~/Views/Shared/_Layout.cshtml";
}
}
Yet every time I click on an 'a' tag, the pjax code doesn't get called. It's as if the selector isn't working when I set up pjax. What am I doing wrong?
UPDATE:
If I do this:
$('document').ready(function () {
$('a').pjax({
container: '#shell',
timeout: 5000
});
});
I see the pjax code getting hit and the Request headers get updated, and the new content loads on the page, but the styling and layout get really messed up and duplicated...
UPDATE:
Inspecting the DOM after this craziness happens reveals that the new page content is getting loaded directly into the anchor that I click, instead of into the element with id #shell. WTF?

You are using a legacy syntax, the new pjax uses the following:
$(document).pjax('a', '#shell', { fragment: '#shell' });
Also I am not familiar with the language you use, but in order to make pjax happen there has to be an HTML element with the id shell in your ViewStart.
As I am not sure about the syntax in that language, try something similar to this for testing:
#{
if (Request.Headers["X-PJAX"] != null) {
echo "<ul id="shell"> pjaaxxx </ul>"; // Would work in php, update syntax
} else {
Layout = "~/Views/Shared/_Layout.cshtml";
}
}

I am not seeing that syntax as valid in the PJax documentation.
Are you sure you didn't mean $(document).pjax('a',{});?
$.pjax immediately executes from what I can tell.

Related

Grails 3.3.9: Call controller action when checkbox is checked

I am fairly new to Grails and frameworks in general, so this is most likely a very basic problem. The only promising looking solutions I was able to find were working with the Tag, which is apparently deprecated in Grails 3. Similar questions do exist, but all from the time when was still a thing.
I am trying to program a way of displaying products that are grouped in subcategories which are then grouped in categories. When my page loads the subcategories and categories are requested from my database and selection options (Select-tag and checkboxes) are rendered in the view.
When one of the checkboxes representing the subcategories is checked i need to run a database query to get the product information and update an HTML-element by rendering a template for every row I get back. I have a controller action that does all that. My only problem is that I need a way to call the controller action whenever one of the checkboxes is checked.
I could maybe work around it by using actionSubmit and a hidden submit button that is clicked by javascript whenever a checkbox is checked, but that doesn’t seem like a proper solution.
I am probably missing some very basic functionality here but I did already thoroughly search and haven’t come across a proper solution by now, probably because I didn't use the right search terms. I would be so happy, if anyone could help me with this. Thanks a lot already!
The following example uses a javascript function activated in response to the checkbox being checked/unchecked, the value of which is passed to an action from which you can do whatever with the value of the checkbox, run your query etc. At present the action renders a template to update the view with the database results.
index.gsp
<!DOCTYPE html>
<html>
<head>
<meta name="layout" content="main" />
<script type="text/javascript">
$(document).ready(function(){
$( '#cb' ).click( function() {
var checked = $(this).is(":checked");
$.ajax( {
url: "/yourController/yourAction?checked=" + checked,
type: "get",
success: function ( data ) {
$( '#resultDiv' ).html( data )
},
error: function(jqXHR, textStatus, errorThrown) {
console.log( 'Error rendering template ' + errorThrown )
}
} );
})
});
</script>
</head>
<body>
<div id="resultDiv"></div>
<g:form>
<g:checkBox name="cb" />
</g:form>
</body>
YourController
class YourController {
def yourAction() {
// you may want to do something with the value of params.checked here?
def dbResults = YourDomain.getStuff()
render ( template: 'theTemp', model: [dbResults: dbResults] )
}
}
_theTemp.gsp
<table>
<caption>Table of stuff</caption>
<g:each in="${dbResults}" var="aThing">
<tr>
<td>${aThing}</td>
</tr>
</g:each>
</table>

How can I add a class to iron router default template?

I've been searching all over and haven't really found an answer to this seemingly very simply problem.
I have an app that has a default template
Router.configure({
layoutTemplate: 'appLayout',
});
<template name="appLayout">
<div id="container">
{{> yield}}
</div>
</template>
Then I have a new route called 'reservations'
Router.route('/reservations',{
name:'reservations',
onAfterAction: function(){
}
});
What I'd like to do is add a class to the default container that uses css transitions to animate background color from white to black.
What I've tried so far is onAfterAction
Router.route('/reservations',{
name:'reservations',
onAfterAction: function(){
$('#container').addClass('black');
}
});
Does nothing, no errors, no anything. So I've tried
Template.reservations.rendered = function () {
setTimeout(function(){
$('#container').addClass('black');
});
};
Which works, but flashes and creates routing problems. You can see the routing issues at crawfish.meteor.com. How can I simply toggle a class after the template is rendered?
You can use the rendered event:
Template.reservations.rendered = function() {
if( ! this.rendered) {
$('#container').addClass('black');
this.rendered = true;
}
};
Note that we check and set rendered. The Template instance then has a 'rendered' variable that we use to prevent re-triggering on re-render (which can run multiple times)

google extension inline install and Verified not working

google.com/webstore i have add my extension
i Have check "This item uses inline install."
Websites: chose Verify site
google.com/webmasters i have add site and Verifyed.
when i put this code on me site:
<link rel="chrome-webstore-item"href="https://chrome.google.com/webstore/detail/itemID">
<button onclick="chrome.webstore.install()" id="install-button">Add to Chrome</button>
<script>
if (document.getElementById('extension-is-installed')) {
document.getElementById('install-button').style.display = 'none';
}
</script>
i click on button "Add to Chrome" install app extension, but when i refresh site button "Add to Chrome" is display. why? i cant Understanding
You're obviously following the guide at https://developer.chrome.com/webstore/inline_installation
In that case, you missed a step.. Let's look at the code.
if (document.getElementById('extension-is-installed')) {
document.getElementById('install-button').style.display = 'none';
}
The condition here is whether an element with ID extension-is-installed is present on the page. But what adds it?
A step back:
For example, you could have a content script that targets the installation page:
var isInstalledNode = document.createElement('div');
isInstalledNode.id = 'extension-is-installed';
document.body.appendChild(isInstalledNode);
So, you need to add a Content Script that adds that element to the page.
However, I doubt that guide will work. By default, content scripts execute after DOM is loaded (and therefore, that hiding script has executed). You can make them run at document_start, but then body does not exist yet.
Let me make an alternative hiding script, based on communicating with the extension using "externally_connectable". Suppose your website is example.com, and your extension's ID is itemID
Add example.com to sites you want to be messaged from:
"externally_connectable" : {
"matches" : [
"*://*.example.com/*"
]
},
In your background page, prepare for the message from the webpage:
chrome.runtime.onMessageExternal.addListener(
function(message, sender, sendResponse) {
if(message.areYouThere) sendResponse(true);
}
);
In your page at example.com, add a button (hidden by default) and code to show it when appropriate:
<button onclick="chrome.webstore.install()"
id="install-button" style="display:none;">
Add to Chrome
</button>
<script>
if (chrome) {
// The browser is Chrome, so we may need to show the button
if(chrome.runtime && chrome.runtime.sendMessage) {
// Some extension is ready to receive messages from us
// Test it:
chrome.runtime.sendMessage(
"itemID",
{areYouThere: true},
function(response) {
if(response) {
// Extension is already installed, keep hidden
} else {
// No positive answer - it wasn't our extension
document.getElementById('install-button').style.display = 'block';
}
}
);
} else {
// Extension is not installed, show button
document.getElementById('install-button').style.display = 'block';
}
}
</script>
Was requested to add page reload after install. chrome.webstore.install has a callback parameter specifically for this.
Instead of using onclick attribute, assign a function:
document.getElementById('install-button').addEventListener("click", function(e) {
chrome.webstore.install(function() {
// Installation successful
location.reload();
});
});

Dijit.MenuItem and <a href=></a> link

My question is similar to that one:
Dijit Menu (bar) with link
I'm using Dijit Menu as in following listing:
<div data-dojo-type="dijit/Menu">
<div id="menuItem" data-dojo-type="dijit/MenuItem">
urlLink
</div>
</div>
But link is not working as it blocked by dojo.stopEvent in _onClick().
The question is:
How to remove dojo.stopEvent and make link inside <div id="menuItem" data-dojo-type="dijit/MenuItem"> work properly?
The issue:
I need to put inside <div id=menuItem"> some code, which has to receive onClick event.
P.S. Originally this is XPages code.
Well I fell in same problem, saw this post and the related other, but wasn't satisfied with the "onclick" solution :
it didn't work (for me) with keyboard navigation
it imposes to a add script element (onclick=...) in the declarative zone which is not what I expect for unobtrusive JavaScript
Finaly I digged further in dojo and decided to directly use the href attribute of first sub-node in the handler. My script section (derived from dijit menus tutorial) is then :
<script>
require([
"dojo/dom",
"dojo/parser",
"dojo/dom-attr",
"dojo/query",
"dijit/registry",
"dijit/WidgetSet", // for registry.byClass
"dijit/Menu",
"dijit/MenuItem",
"dijit/MenuBar",
"dijit/MenuBarItem",
"dijit/PopupMenuBarItem",
"dojo/domReady!"
], function(dom, parser, domattr, query, registry){
// a menu item selection handler
var onItemSelect = function(event){
dom.byId("lastSelected").innerHTML = this.get("label");
var achild = query("a", this.domNode)[0];
if (achild != null) {
var href = domattr.get(achild, "href");
if ((href != null) && (href != '') && (href != '#')) {
window.location.href = href;
}
}
};
parser.parse();
var setClickHandler = function(item){
item.on("click", onItemSelect);
};
registry.byClass("dijit.MenuItem").forEach(setClickHandler);
registry.byClass("dijit.MenuBarItem").forEach(setClickHandler);
});
</script>
That way I don't have to change anything in a menu of type
<ul><li>...</li></ul>
that works with JavaScript disabled, and links work fine with mouse and keyboard navigation when JavaScript is enabled. Simply don't forget the "class='claro'" in body element ....
What about this:
<div data-dojo-type="dijit/Menu">
<div id="menuItem" data-dojo-type="dijit/MenuItem"
onclick="window.location('http://url.com')">
urlLink
</div>
</div>
Working jsfiddle:
http://jsfiddle.net/KuyYX/

jQuery Masonry infinite scroll and picture overlap problems with my tumblr theme

I am new in programming(javascript) but I've done quite a research the past few days in order to make my tumblr theme work correctly. I know my question is common but as it seems I don't have enough knowledge to integrate correctly parts of code that were given in many similar examples.
My theme is supposed to override the "15 posts per page" limitation of tumblr and with an "endless scroll" option it should put all my posts (all of them pictures) in one endless page. Well, It doesn't. With a little help from here, I managed to wrap my {block:Posts} with the and with a couple of random changes in the masonry() call I ended up with this
As you can see my pictures are not overlapping (at last!) but after the 15 first posts it looks like a new page is created and the last pictures are not correctly aligned.
my jQuery masonry code is this:
<script type="text/javascript">
$(window).load(function () {
$('.autopagerize_page_element').masonry(),
$('.autopagerize_page_element').infinitescroll({
navSelector : "div.navigation",
// selector for the paged navigation (it will be hidden)
nextSelector : "div.navigation a#nextPage",
// selector for the NEXT link (to page 2)
itemSelector : ".autopagerize_page_element",
// selector for all items you'll retrieve
bufferPx : 10000,
extraScrollPx: 12000,
loadingImg : "http://b.imagehost.org/0548/Untitled-2.png",
loadingText : "<em></em>",
},
// call masonry as a callback.
function() { $('.autopagerize_page_element').masonry({ appendedContent: $(this) }); }
);
});
</script>
I know, its a mess...
Would really appreciate some help.
I'm not used to work with tumblr, but I can what is happening:
Line 110:
This script is creating a wrapper div around the entries each time you call to masonry, because of the script, each load looks like a new page, I think you can simply remove it.
Some tips:
You don't have to wait $(windows).load to execute masonry, change it by $(function()
To avoid image overlapping use appened masonry method and imagesLoad: Refer this
I see you're using masonry 1.0.1, be sure you're using masonry last version (2.1.06)
Example code:
$(function() {
//$('.autopagerize_page_element').masonry();
var $container = $('.autopagerize_page_element');
//wait until images are loaded
$container.imagesLoaded(function(){
$container.masonry({itemSelector: '.entry'});
});
$('.autopagerize_page_element').infinitescroll({
navSelector : "div.navigation",
// selector for the paged navigation (it will be hidden)
nextSelector : "div.navigation a#nextPage",
// selector for the NEXT link (to page 2)
itemSelector : ".entry",
// selector for all items you'll retrieve
bufferPx : 10000,
extraScrollPx: 12000,
loadingImg : "http://b.imagehost.org/0548/Untitled-2.png",
loadingText : "<em></em>",
},
// call masonry as a callback.
//function() { $('.autopagerize_page_element').masonry({ appendedContent: $(this) }); }
function( newElements ) {
// hide new items while they are loading
var $newElems = $( newElements ).css({ opacity: 0 });
// ensure that images load before adding to masonry layout
$newElems.imagesLoaded(function(){
// show elems now they're ready
$newElems.animate({ opacity: 1 });
$container.masonry( 'appended', $newElems, true );
});
}
);
});
and be sure to remove the last script in this header block:
<script type="text/javascript" src="http://static.tumblr.com/imovwvl/dJWl20ley/jqueryformasonry.js"></script>
<script type="text/javascript" src="jquery.masonry.min.js"></script> <!-- last masonry version -->
<script src="http://static.tumblr.com/df28qmy/SHUlh3i7s/jquery.infinitescroll.js"></script>
<!--<script src="http://static.tumblr.com/thpaaos/lLwkowcqm/jquery.masonry.js"></script>-->
Hope it helps

Resources