Jquery .change() event fires only once - javascript

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.

Related

Remove dynamically added div on timer

I'd like a div to appear for a short duration of time and then go away.
So, I dynamically create the div on the click of a button, and then after some work is done, I'd like it to be removed from the DOM.
So, I set up a timer like so:
var contentJoinTab = $("#...");
var divIdSubscribePleaseWait = "div-subscribe-pleasewait";
btnSubscribe.on("click", function (event) {
displaySubscriptionWait();
postMailingListSubscription();
});
function displaySubscriptionWait() {
var s = `<div id = ${divIdSubscribePleaseWait} class = "${classMailingListPleaseWait}">Please wait...</div>`;
contentJoinTab.append(s);
};
function postMailingListSubscription() {
// fake for now
window.setTimeout(function() {
removeSubscriptionWait();
}, 4000);
};
function removeSubscriptionWait() {
contentJoinTab.parent(`${divIdSubscribePleaseWait}`).remove();
// I've even tried the following to no avail
// $(`${divIdSubscribePleaseWait}`).remove();
// contentJoinTab.find(`${divIdSubscribePleaseWait}`).remove();
};
However, even though there is no error in the call to the remove() method, the div I am trying to remove remains in the DOM and is visible.
I do understand event propagation but my understanding is that that's not relevant here. That would have been relevant if I wanted to attach an event to the click (or any other event) of the dynamically created div or any of its parent.
You may be missing # when calling removeSubscriptionWait And also need "" for id = ${divIdSubscribePleaseWait}.
Please see changes below in case it isn't clear:
function displaySubscriptionWait() {
var s = `<div id = "${divIdSubscribePleaseWait}" class = "${classMailingListPleaseWait}">Please wait...</div>`;
contentJoinTab.append(s);
};
function postMailingListSubscription() {
// fake for now
window.setTimeout(function() {
removeSubscriptionWait();
}, 4000);
};
function removeSubscriptionWait() {
contentJoinTab.parent(`#${divIdSubscribePleaseWait}`).remove();
// I've even tried the following to no avail
$(`#${divIdSubscribePleaseWait}`).remove();
};
You can do that by setting outerHTML of that div to null
function addDiv() {
let s = "<div id='tempDiv'>Temporary Div</div>"
let root = document.getElementById("root")
root.innerHTML += s;
}
function removeDiv() {
let theDiv = document.getElementById("tempDiv");
theDiv.outerHTML=""
}
addDiv()
setTimeout(removeDiv,2000)
<div id=root>
</div>
You have appended that div as a child of contentJoinTab but when you go to remove it you are looking for it as being parent of contentJoinTab
You also need to add the ID prefix in selector
try changing
contentJoinTab.parent(`${divIdSubscribePleaseWait}`).remove();
To
contentJoinTab.find(`#${divIdSubscribePleaseWait}`).remove();
update removeSubscriptionWait function :
function removeSubscriptionWait() {
contentJoinTab.find('#'+`${divIdSubscribePleaseWait}`).remove();
};

Add or Delete jQuery sortable element and remember order

I'm implementing something similar to this in one of my Wordpress metabox. User should be able to add and remove jquery-ui sortable elements and remember the position(order) of the elements exists.
I already know how to remember the position(order) when the elements are resorted by dragging and dropping.
jQuery(document).ready(function () {
jQuery('ul').sortable({
stop: function (event, ui) {
var data = jQuery(this).sortable('toArray');
jQuery('#elements-order').val(data);
}
});
});
This will output an array which contains the order like 1,2,3,5,4 But, when new elements are added or elements are deleted, how to make this code run to remember the order of the new elements.
This is the code I use to Add elements
jQuery(document).ready(function () {;
var wrapperSize = jQuery("#element-area-top").width();
(function () {
jQuery(".add-element").on("click", ".add-item", function () {
var start = jQuery("#sortable"),
selectBoxVal = jQuery("#element-list").val();
var element = null;
element = ('<li></li>');
var newRow = jQuery(element);
jQuery(start).append(newRow);
jQuery("#elements-order").val(jQuery('#elements-order').val() + i+',');
});
})();
This is the code I use to delete elements
jQuery("#sortable").on("click", ".delete", function () {
jQuery(this).parents(/*someelement*/).remove();
});
So, could anyone know how to do this ?
You can get sort order with same logic in add/delete functions as well (just replace this with '#ul').
var data = jQuery('#ul').sortable('toArray');
jQuery("#elements-order").val(data);
Or even better, put above code in a common function and just call common function. Here is updated fiddle demonstrating same.

Handling State changes jQuery and History.js

Ok, so I need some insight into working with History.js and jQuery.
I have it set up and working (just not quite as you'd expect).
What I have is as follows:
$(function() {
var History = window.History;
if ( !History.enabled ) {
return false;
}
// Capture all the links to push their url to the history stack and trigger the StateChange Event
$('.ajax-link').click(function(e) {
e.preventDefault();
var url = this.href; //Tells us which page to load
var id = $(this).data('passid'); //Pass ID -- the ID in which to save in our state object
e.preventDefault();
console.log('url: '+url+' id:'+id);
History.pushState({ 'passid' : id }, $(this).text(), url);
});
History.Adapter.bind(window, 'statechange', function() {
console.log('state changed');
var State = History.getState(),
id = State.data.editid; //the ID passed, if available
$.get(State.url,
{ id: State.data.passid },
function(response) {
$('#subContent').fadeOut(200, function(){
var newContent = $(response).find('#subContent').html();
$('#subContent').html(newContent);
var scripts = $('script');
scripts.each(function(i) {
jQuery.globalEval($(this).text());
});
$('#subContent').fadeIn(200);
});
});
});
}); //end dom ready
It works as you'd expect as far as changing the url, passing the ID, changing the content. My question is this:
If I press back/forward on my browser a couple times the subContent section will basically fadeIn/fadeOut multiple times.
Any insight is appreciated. Thanks
===================================================
Edit: The problem was in my calling all of my <script> and Eval them on each statechange. By adding a class="no-reload" to the history controlling script tag I was able to do:
var scripts = $('script').not('.no-reload');
This got rid of the problem and it now works as intended. Figure I will leave this here in case anyone else runs into the same issue as I did.
The problem was in my calling of all of my <script> and Eval them on each statechange. By adding a class="no-reload" to the history controlling script tag I was able to do:
var scripts = $('script').not('.no-reload');
This got rid of the problem and it now works as intended. Figure I will leave this here in case anyone else runs into the same issue as I did.

Javascript Singleton design pattern and closure

I'm trying to create a Singleton object that deals with servicing an event listener:
var ChildParent = (function () {
var html_element = document.getElementById("quoteNum");
var row_number = 0;
return {
init: function(){
html_element["parenttype"+row_number].addEventListener("click", ChildParent.fire, false);
},
add: function(total) { //Adding a row
},
fire: function() {
alert("it fired!");
}
}
})();
However, when I call ChildParent.init(), the document-element will not get assigned to html_element, so i can't attach the listener. Oddly enough, the row_number variable is initialized to zero. Is there some sort of scoping conflict that I don't understand? When i use the step-into feature of opera's dragonfly, I can't create var assignments when in the init() function.
Make sure element with id "quoteNum" is available on the page when you are executing your script.
It may happen that you are executing the script without waiting for all the page elements to be rendered.
You may think about handling window.onload.
Update
the following change could help you fix the issue with html_element being initialized before the page is rendered.
var ChildParent = (function () {
function getElement(){
return html_element ? html_element : html_element = document.getElementById("quoteNum");
}
var html_element;
var row_number = 0;
return {
init: function(){
getElement()["parenttype"+row_number].addEventListener("click", ChildParent.fire, false);
},
add: function(total) { //Adding a row
},
fire: function() {
alert("it fired!");
}
}
})();
Is the above code executed after the element with id quoteNum exists in the DOM?
If not html_element will be null.
So make sure that all the above code is in a script tag that occurs somewhere in the document below the element (or is in a window.onload jQuery's document ready type event).

Resend AJAX request with link?

Is there anyway to reload just the AJAX request, so that it updates the content pulled from the external site in the code below?
$(document).ready(function () {
var mySearch = $('input#id_search').quicksearch('#content table', { clearSearch: '#clearsearch', });
var container = $('#content');
function doAjax(url) {
if (url.match('^http')) {
$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent(url)+
"%22&format=xml'&callback=?",
function (data) {
if (data.results[0]) {
var fullResponse = $(filterData(data.results[0])),
justTable = fullResponse.find("table");
container.append(justTable);
mySearch.cache();
$('.loading').fadeOut();
} else {
var errormsg = '<p>Error: could not load the page.</p>';
container.html(errormsg);
}
});
} else {
$('#content').load(url);
}
}
function filterData(data) {
data = data.replace(/<?\/body[^>]*>/g, '');
data = data.replace(/[\r|\n]+/g, '');
data = data.replace(/<--[\S\s]*?-->/g, '');
data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g, '');
data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g, '');
data = data.replace(/<script.*\/>/, '');
data = data.replace(/<img[^>]*>/g, '');
return data;
}
doAjax('link');
});
Right now I have a button which reloads the entire page, but I just want to reload the AJAX request. Is this even possible?
Edit: I need to specify more. While it can easily call the AJAX again, can it also replace the info that is already there?
You just need to call the doAjax function again on button click...
$("#buttonID").on("click", function() {
doAjax("link");
});
Add that into the above document.ready code and set the button ID correspondingly.
Then change
container.append(justTable);
to
container.html(justTable);
In your doAjax function you append HTML onto an element. If you overwrite the element's HTML instead of appending to it then the HTML will be "refreshed" each time the doAjax function runs:
Simply change:
container.append(justTable);
To:
container.html(justTable);
And of-course you can bind a click event handler to a link (or any element) like the rest of the answers show. Make sure you bind the click event in the proper scope (inside the document.ready event handler) so the doAjax function will be accessible from the click event handler.

Categories

Resources