AJAX URL append conflicting with stored jQuery .data() - javascript

I've got a document.ready function that stores all of the data in preparation for a popover on :hover.
domReady( function() {
$('.foo').each( function() {
var el = $(this);
var el_content = el.find('[data-content]');
el.data( 'content-attr', { content: el_content, classes: el_classes } );
} );
} );
Everything works fine by default, but when the URL is appended for AJAX sorting, I lose my window ref I suppose, because the following event handler returns undefined when accessing the data which is accessed without issue when the URL is not appended. I'm aware that this must be a window reference issue in the event handler, can someone point me to the correct way to reference window so that that the jQuery object where data is stored on load is accessible to .on( 'hover', function() { //do stuff }); while the URL is appended for AJAX?
$( window ).on( 'hover', '[rel="popover"]', function() {
var el = $(this);
var this_content_data = el.data( 'content-attr' ).content;
function() {
// do stuff
}
} );

In the case of this particular issue, I realized the only way to do this was to store the data in a jQuery .data attribute on the initialization of the view for access by the function on $(window).element.on( 'hover', ...){}.

Related

jQuery error on Custom Javascript variable in Google tag manager

Why am I getting an error when I run a jquery as a Custom javasript variable? The error description is "Error at line 10, character 2: Parse error. ')' expected"
function(){
$( document ).ready(function() {
$('button[class="panel__link panel__link--btb"]').on( 'click', function(e) {
var $label = $( this ).parent().find("h2").text();
return $label;
});
});
};
Please advise.
Regards,
Sree
Remove the last semicolon ; on the last line:
function(){
$( document ).ready(function() {
$('button[class="panel__link panel__link--btb"]').on( 'click', function(e) {
var $label = $( this ).parent().find("h2").text();
return $label;
});
});
}
I think you did some conceptual mistake, when you working with GTM. Custom variable should return some value when trigger is fired.
I think your initial goal in GTM is:
Send some tag (to Universal analytics or something else) when user clicks on button button[class="panel__link panel__link--btb"]. This tag should contain some text information, which you can find like that .parent().find("h2").text();
If i am correct, then you should do the following:
Go to Variables. Built-in variables-> Configure-> Enable Click Element
Go to Triggers -> New -> Type: All Elements -> Click Element:matches CSS selector:button.panel__link.panel__link--btb
Go to Variables. New -> Custom JavaScript: function(){return {{Click Element}}.parent().find("h2").text();} -> Name: 'H2 text'
Go to Tags. New -> Assign trigger from step #2. -> Type: (you can choose what you need) -> And here you can use your variable {{H2 text}}, it will return necessary text
The error is caused because there no name for the function. I think you are trying to do a Self Invoking function which should be
(function(){
//your code
}());
Your code should be,
(function(){
$( document ).ready(function() {
$('button[class="panel__link panel__link--btb"]').on( 'click', function(e) {
var $label = $( this ).parent().find("h2").text();
return $label;
});
});
}());
Or
Remove the function() {} and simply execute the code with .ready
$( document ).ready(function() {
$('button[class="panel__link panel__link--btb"]').on( 'click', function(e) {
var $label = $( this ).parent().find("h2").text();
return $label;
});
});

Jquery .change() event fires only once

So I'm fairly novice with jquery and js, so I apologise if this is a stupid error but after researching I can't figure it out.
So I have a list of data loaded initially in a template, one part of which is a dropdown box that lets you filter the data. My issue is that the filtering only works once? As in, the .change function inside $(document).ready() only fires the once.
There are two ways to reload the data, either click the logo and reload it all, or use the search bar. Doing either of these at any time also means the .change function never fires again. Not until you refresh the page.
var list_template, article_template, modal_template;
var current_article = list.heroes[0];
function showTemplate(template, data)
{
var html = template(data);
$("#content").html(html);
}
$(document).ready(function()
{
var source = $("#list-template").html();
list_template = Handlebars.compile(source);
source = $("#article-template").html();
article_template = Handlebars.compile(source);
source = $("#modal-template").html();
modal_template = Handlebars.compile(source);
showTemplate(list_template,list);
$(".articleButton").click(function()
{
var index = $(this).data("id");
current_article = list.heroes[index];
showTemplate(article_template,current_article);
$('.poseThumb').click(displayModal);
});
$("#classFilter").change(function()
{
console.log("WOW!");
var classToFilter = this.value;
var filteredData =
{
heroes: list.heroes.filter(function(d)
{
if (d.heroClass.search(classToFilter) > -1)
{
return true;
}
return false;
})
};
console.log(filteredData);
showTemplate(list_template,filteredData);
$(".articleButton").click(function()
{
var index = $(this).data("id");
current_article = filteredData.heroes[index];
showTemplate(article_template,current_article);
$('.poseThumb').click(displayModal);
});
});
$("#searchbox").keypress(function (e)
{
if(e.which == 13)
{
var rawSearchText = $('#searchbox').val();
var search_text = rawSearchText.toLowerCase();
var filteredData =
{
heroes: list.heroes.filter(function(d)
{
if (d.name.search(search_text) > -1)
{
return true;
}
return false;
})
};
console.log(filteredData);
showTemplate(list_template,filteredData);
$(".articleButton").click(function()
{
var index = $(this).data("id");
current_article = filteredData.heroes[index];
showTemplate(article_template,current_article);
$('.poseThumb').click(displayModal);
});
}
});
$("#logo").click(function()
{
showTemplate(list_template,list);
$(".articleButton").click(function()
{
var index = $(this).data("id");
current_article = list.heroes[index];
showTemplate(article_template,current_article);
$('.poseThumb').click(displayModal);
});
});
//$("#logo").click();
});
function displayModal(event)
{
var imageNumber = $(this).data("id");
console.log(imageNumber);
var html = modal_template(current_article.article[0].vicPose[imageNumber]);
$('#modal-container').html(html);
$("#imageModal").modal('show');
}
I should note two things: first, that the search bar works perfectly, and the anonymous function inside both of them is nearly identical, and like I said, the filtering works perfectly if you try it after the initial load. The second is that the same problem occurs replacing .change(anonymous function) with .on("change",anonymous function)
Any help or advice would be greatly appreciated. Thanks.
I agree with Fernando Urban's answer, but it doesn't actually explain what's going on.
You've created a handler attached to an HTML element (id="classFilter") which causes part of the HTML to be rewritten. I suspect that the handler overwrites the HTML which contains the element with the handler on it. So after this the user is clicking on a new HTML element, which looks like the old one but doesn't have a handler.
There are two ways round this. You could add code inside the handler which adds the handler to the new element which has just been created. In this case, that would mean making the handler a named function which refers to itself. Or (the easier way) you could do what Fernando did. If you do this, the event handler is attached to the body, but it only responds to clicks on the #classFilter element inside the body. In other words, when the user clicks anywhere on the body, jQuery checks whether the click happened on a body #classFilter element. This way, it doesn't matter whether the #classFilter existed when the handler was set. See "Direct and delegated events" in jQuery docs for .on method.
Try to use some reference like 'body' in the event listeners inside your DOM like:
$('body').on('click','.articleButton', function() {
//Do your stuff...
})
$('body').on('click','#classFilter', function() {
//Do your stuff...
})
$('body').on('keypress','#searchbox', function() {
//Do your stuff...
})
$('body').on('click','#logo', function() {
//Do your stuff...
})
This will work that you can fire it more than once.

Select from json on click

I'm trying to select a row from a json array using jquery. This is what i have:
$(document).ready(function() {
$.getJSON( "js/collectie.json", function(data) {
jsoncollectie = data;
})
$( "#collectie li" ).click(function(){
var thumb_id = $(this).data("id");
for(var i = 0; i < jsoncollectie.stoelen.length; i++){
if(jsoncollectie.stoelen[i].ref == thumb_id){
$("#detailimage").attr('src', jsoncollectie.stoelen[i].image);
$("#detailimage").attr('title', jsoncollectie.stoelen[i].title);
$("#title").html('<h4> '+jsoncollectie.stoelen[i].naam+' </h4>');
$("#secondaryimage").attr('src', jsoncollectie.stoelen[i].secondaryimage);
$("#secondaryimage").attr('title', jsoncollectie.stoelen[i].secondarytitle);
$("#description").html('<p> '+jsoncollectie.stoelen[i].description+' </p>');
}
}
});
});
Now when i click on a list item (#collectie li) the console outputs "ReferenceError: jsoncollectie is not defined". I don't know why it's doing that and i'm pretty sure it worked two weeks ago. Don't know much about javascript/jquery yet, but i'm slowly learning.
$(document).ready(function()
{
// Provide access to data outside of the getJSON call
var m_oJsonCollectie = null;
// Get the data
$.getJSON( "js/collectie.json", function(data)
{
// Set the data
m_oJsonCollectie = data;
// Apply the click handler
$( "#collectie li" ).click(function()
{
var thumb_id = $(this).data("id");
for(var i = 0; i < m_oJsonCollectie.stoelen.length; i += 1)
{
if(m_oJsonCollectie.stoelen[i].ref == thumb_id)
{
$("#detailimage") .attr('src', m_oJsonCollectie.stoelen[i].image);
$("#detailimage") .attr('title', m_oJsonCollectie.stoelen[i].title);
$("#title") .html('<h4> '+ m_oJsonCollectie.stoelen[i].naam+' </h4>');
$("#secondaryimage").attr('src', m_oJsonCollectie.stoelen[i].secondaryimage);
$("#secondaryimage").attr('title', m_oJsonCollectie.stoelen[i].secondarytitle);
$("#description") .html('<p> '+ m_oJsonCollectie.stoelen[i].description+' </p>');
}
}
});
});
});
JS have block level scope, so you wont get the values outside of the function unless you provide access to them or they are declared in global scope (which is considered bad practice).
This pattern should help you keep your data accessible, and only applies the click handler if the getJSON call is successful.
Check that your getJSON request is being received and returned by using deferred methods
// Syntax that will shed light to your issue :
$.getJSON
(
"js/collectie.json",
function (oJSON) { /*success*/ }
)
.done(function() { /* succeeded */ })
.fail(function() { /* failed */ })
.always(function() { /* ended */ });
I came to this conclusion due to comments and the fact that a variable only declared in the success handler for getJSON was undefined. Since the JSON containing variable was undefined, the success handler must never have been called. Chances are that the path to the JSON you are trying to get is incorrect.
Documentation for the methods to accomplish :
getJSON
done
fail
always
UPDATE
Knowing that the response is 304, and the results are undefined are the important details here. This issue has been addressed by jQuery already here
This is actually correct, given the ifModified header has not been set to false.
To fix this issue, use ajaxSetup() to modify the header.
NOTE : the use of this method is not recommended by jQuery, but in this case it works.
// place this is document ready handler before making any calls.
$.ajaxSetup({ ifModified : false });

pass value/variable from fancybox iframe to parent

I'am trying to pass a variable/ value from the fancybox iframe to the parent window without success.
Fancybox is launched from a link with
class="fancybox fancybox.iframe"
My code in the fancybox.iframe is:
$(document).ready(function(){
$('.insert_single').click(function(){
var test = $('.members_body').find('{row.U_USERNAME}');
setTimeout(function(){ parent.$.fancybox.close();},300);return true;
});
});
Where '{row.U_USERNAME}' is the username to find in the iframe.
Then, in the parent there's the following code:
$(document).ready(function(){
$('.fancybox').fancybox(
{
openEffect:'fade',
openSpeed:500,
afterClose: function(){
alert($(".fancybox-iframe").contents().find(test));
$('#form input[name=username]').val()(test);return false;
}
}
);
});
But when the fancybox is closed, there's no alert showing up with the variable "test", nor the variable is showing up as a value or as a text in the input field of the form.
I've read and tried various solutions found here on stackoverflow without success.
Thanks in advance for helping
EDIT
Here's an Example
When the fancybox is closed the iframe is removed from the document. So you must use beforeClose event instead of afterClose
$(document).ready(function() {
$('a.fancybox').fancybox({
openEffect:'fade',
openSpeed:500,
beforeClose: function() {
// working
var $iframe = $('.fancybox-iframe');
alert($('input', $iframe.contents()).val());
},
afterClose: function() {
// not working
var $iframe = $('.fancybox-iframe');
alert($('input', $iframe.contents()).val());
}
});
});
JSFiddle: http://jsfiddle.net/NXY7Y/1/
EDIT:
I edited your jsfiddle (http://jsfiddle.net/NXY7Y/9/). Update is in this link
http://jsfiddle.net/NXY7Y/13/
Main page javscript:
$(document).ready(function() {
$('a.fancybox').fancybox({
openEffect:'fade',
openSpeed:500//,
//beforeClose: function() {
// // working
// var $iframe = $('.fancybox-iframe');
// alert($('input', $iframe.contents()).val());
//},
//afterClose: function() {
// // not working
// var $iframe = $('.fancybox-iframe');
// alert($('input', $iframe.contents()).val());
//}
});
});
function setSelectedUser(userText) {
$('#username').val(userText);
}
No need to use afterClose or beforeClose events. Just access the parent function setSelectedUser from the iframe on link click event like this:
$(document).ready(function() {
$('a.insert_single').click(function() {
parent.setSelectedUser($(this).text());
parent.$.fancybox.close();
});
});
Some clarifications :
You should use .find() to find elements by selector (you are trying to find a variable .find(test), which is not a valid format).
You should use .val() to get the contents of an input field or .val(new_value) to set the contents of an input field
You should use .html() or .text() to get the contents of any element other than input,
example: having this html code
<p class="test">hola</p>
... and this jQuery code
var temp = $(".test").html();
... temp will return hola.
On the other hand, if you have control over the iframed page and it's under the same domain than the parent page, then you may not need to set any jQuery in the child page.
so, having this html in the child (iframed) page for instance
<div class="members_body">
<p>GOOGLE</p>
<p>JSFIDDLE</p>
<p>STACKOVERFLOW</p>
</div>
You could set this jQuery in your parent page to get the contents of any clicked element in your child page :
var _tmpvar; // the var to use through the callbacks
jQuery(document).ready(function ($) {
$(".fancybox").fancybox({
type: "iframe",
afterShow: function () {
var $iframe = $('.fancybox-iframe');
$iframe.contents().find(".members_body p").each(function (i) {
$(this).on("click", function () {
_tmpvar = $('.members_body p:eq(' + i + ')', $iframe.contents()).html();
$.fancybox.close();
}); // on click
}); // each
},
afterClose: function () {
$('#form input[name=username]').val(_tmpvar);
}
});
}); // ready
Notice that we declared the var _tmpvar globally so we can use it within different callbacks.
See JSFIDDLE

Jquery doesnot bind events to ajax added dom

I have an ajax function that loads the content of 4 checkboxes as follows:
$.ajax({
url : some url..,
dataType : 'json',
success : function(data) {
buildCheckboxes(data);
},
error : function(data) {
do something...
}
});
build checkboxes methods does something like this:
function updateNotificationMethods(items) {
var html = [];
$.each(items, function(i, item) {
htmlBuilder = [];
htmlBuilder.push("<input type='checkbox' class='checkbox-class' name='somename' value='");
htmlBuilder.push(item.id);
htmlBuilder.push("'");
htmlBuilder.push("/> ");
htmlBuilder.push(item.name);
htmlBuilder.push("<br/><br/>")
html.push(htmlBuilder.join(''));
});
$("#div").html(html.join(''));
}
i have also an event binder that should be triggered when checkbox value changes:
$(".checkbox-class").change(function() {
alert("change");
});
it works if i have the checkboxes html in the source (i.e. static) as opposed to the set up i have here, where i dynamically load the data from server.
is there something i can do so that binding take place timely?
peace!
This is because the element is not present when you bind your handler.
Try this:
$( document ).on( 'change', '.checkbox-class', function() {
alert("change");
});
Or if you are using an older version of jQuery (less than 1.7) ...
$( '.checkbox-class' ).live( function() {
alert("change");
});
Checkboxes are not available while you are binding the events. jsfiddle
Assuming that element with id div is present while binding the event.
$("#div").on("change",".checkbox-class",function() {
alert("change");
});
This code:
$(".checkbox-class").change(function() {
alert("change");
});
do not establishes a continuous and on-going rule, instead, this code attaches an event manager (in this case to the change event) to each matching DOM object that exists at the moment it is executed.
If you want you can re-execute this code (or one similar and narrow) each time you add checkboxes to the DOM.

Categories

Resources