Event handler doesn't work anymore after html rerendering - javascript

I have the following structure in my js file:
$.getJSON("data/file.json")
.done(function(data) {
var loadHTMLfunction = /* some code */
loadHTMLfunction();
// updates display based on user filter selection
$("#select-section").on("change", function() {
$("article").find(".myClass").remove();
loadHTMLfunction();
});
// text swap event
$(".summary-link").on("click", function() {
var el = $(this),
tmp = el.text();
el.text(el.data("text-swap"));
el.data("text-swap", tmp);
});
})
.fail(function(jqxhr, textStatus, error) {
// error handling
});
my issue is that my text swap event works well when the page is loaded for the first time but it doesn't work anymore once the user used the selection event (this event is a select html element to update display).
Is there something wrong in my js file structure or something wrong in my code (or in both!)?
Thanks!

I feel the coupling on your functions are too tight. Once $.getJSON.done, you should really just assign the data to a variable and bind your event handlers outside of your scope of the ajax call. A refactored version of the code might look something like this:
(function() {
var storedData;
$.getJSON("data/file.json", function(data) {
storedData = data;
});
.error(function(jqXHR, textStatus, errorThrown) {
alert("error: " + textStatus + ", Description: " + jqXHR.responsetext);
});
var loadHTMLfunction = function() {
// your code
};
loadHTMLfunction(); // You ought to tell us what this function is
// else we don't know if it's redundant or not
// to run so repetitively.
$("#select-section").on("change", function() {
$("article").find(".myClass").remove();
loadHTMLfunction(); // I feel like this is an issue.
});
$(".summary-link").on("click", function() {
var el = $(this),
tmp = el.text();
el.text(el.storedData("text-swap"));
el.storedData("text-swap", tmp);
});
}());

You should include
// text swap event
$(".summary-link").on("click", function() {
var el = $(this),
tmp = el.text();
el.text(el.data("text-swap"));
el.data("text-swap", tmp);
});
in the function loadHTMLfunction.
loadHTMLfunction = function(){
//your code
// text swap event
$(".summary-link").on("click", function() {
var el = $(this),
tmp = el.text();
el.text(el.data("text-swap"));
el.data("text-swap", tmp);
});
}
You probably are doing some action that removes the element ".summary-link" and you just bind event first time.

Related

Adding event handler to non-existent class?

I've seen questions that relate to non-existent elements, but not non-existent classes. Here's what I want to do. When a button of class "see_answer" is clicked, I want to remove the class and replace it with "see_question". However, my click function for a button, once its class is "see_question", is not running. I have tried $(document).on("click", ".see_question", function(event ) and I have tried $(".see_question").on("click", function(event) {etc.... Thanks for the help! My code is below:
$(document).ready(function() {
// initialize variables
var lang = "javascript";
var qno = 1;
var prevText; // holds question/answer
var language = lang + ".html";
// set up tabs, and keep track of which one is clicked
$("#myTabs").tabs({
activate: function (event, ui) {
var active = $("#myTabs").tabs("option", "active");
lang = $("#myTabs ul > li a").eq(active).attr("href");
lang = lang.replace("#", "");
}
});
/* REMINDERS
actual qa part: blah_language
*/
// set up question
$.ajax({
url: language,
dataType: "html",
success: function(data) {
$("#blah_"+lang)
.text($(data).find("#1").text());
},
error: function(r) {
alert("whoops, error in initialization");
}
});
$(".next_question").on("click", function(event) {
event.preventDefault();
var id = $(this).attr("id").replace("next_question_", "");
var language = id + ".html";
var doc = "#blah_" + id;
$.ajax({
url: language,
dataType: "html",
success: function(data) {
var num = "#" + qno;
$(doc)
.text($(data).find(num).text());
qno = qno + 1;
},
error: function(r) {
alert("whoops");
}
});
prevText = "";
});
// SHOW ANSWER
$(".see_answer").on("click", function(event) {
event.preventDefault();
var id = $(this).attr("id").replace("see_answer_", "");
var prev = "#blah_" + id;
var answers = id + "_answers.html";
// Save the question
prevText = $(prev).text();
var obj = $(this);
$.ajax({
url: answers,
dataType: "html",
success: function(data) {
var num = "#" + 3;
$(prev)
.text($(data).find(num).text());
},
error: function(r) {
alert("whoops");
}
});
obj.val("See Question");
obj.removeClass("see_answer");
obj.addClass("see_question");
event.stopPropagation();
});
$(document).on("click",".see_question", function(event) {
event.preventDefault();
obj = $(this);
event.preventDefault();
var id = $(this).attr("id").replace("see_answer_", "");
var prev = "#blah_" + id;
$(prev).text(prevText);
obj.val("See Answer");
obj.removeClass("see_question");
obj.addClass("see_answer");
});
})
Click handling for .see_question elements is delegated to document. For .see_answer elements, a click handler is attached directly. Therefore, swapping the class names will have an undesirable effect.
when see_answer is in force, a click will trigger the "see_answer" handler.
when see_question is in force, a click will trigger the "see_question" handler AND the "see_answer" handler, which is still attached.
There's a number of ways to do this properly. From where you currently are, the simplest solution is to delegate click handling of .see_question and .see_answer elements to document.
$(document).on("click", ".see_answer", function(event) {
...
});
$(document).on("click", ".see_question", function(event) {
...
});
Combine the 2 handlers and figure out which version it is by hasClass() before you change the classes around
$(document).on("click", ".see_question, .see-answer", function(event ){
var $btn =$(this), isAnswer = $btn.hasClass('see_answer');
// we know which one it is so can switch classes now
$btn.toggleClass('see_answer see_question');
if(isAnswer){
/* run code for answer version */
}else{
/* run code for question version */
}
});

Click event object tracking woes

So I am working on this but of jQuery that gets the element id through a click event. This then triggers a function that acts like the deprecated .toggle()- it slides an element down on the fist click and slides that element up on the second click. However, there is a bug that causes the element to slide up and down the amount of times that it has been clicked on. For instance, if this is the second time I use the .clickToggle function, the element (table) slides up and down twice before settling, and so on. I suspect it has something to do with the event object, e, tracking the number of clicks-- i.e. I probably shouldn't set id = e.target.id-- but I'm not sure how to fix while still getting the relevant element id that I need.
Here is the relevant clickToggle plug in (courtesy of an answer here on stackoverflow).
(function($) {
$.fn.clickToggle = function(func1, func2) {
var funcs = [func1, func2];
this.data('toggleclicked', 0);
this.click(function() {
var data = $(this).data();
var tc = data.toggleclicked;
$.proxy(funcs[tc], this)();
data.toggleclicked = (tc + 1) % 2;
});
return this;
};
}(jQuery));
Here is the buggy code that fits the above description.
$(document).click(function(e) {
//get the mouse info, and parse out the relevant generated div num
var id = e.target.id;
var strId = id.match(/\d$/);
//clickToggle the individual table
$('#showTable' + strId).clickToggle(function () {
$('#table' + strId).slideDown();
$('#table' + strId).load('files.php');
},
function () {
$('#table' + strId).slideUp();
});
});//close mousemove function
Any help would be much appreciated. Thanks.
The problem is that you're registering a new click handler for the element each time you invoke clickToggle:
this.click(function() {...
On each subsequent click, you add another handler, as well as invoking all previous handlers. Bleagh.
Better to be straightforward: (DEMO)
var showTable = function($table) {
$table.slideDown();
$table.load('files.php');
$table.removeClass('hidden');
};
var hideTable = function($table) {
$table.slideUp();
$table.addClass('hidden');
};
$(document).click(function (e) {
//get the mouse info, and parse out the relevant generated div num
var id = e.target.id;
var strId = id.match(/\d$/)[0];
var $table = $('#table' + strId);
if ($table.hasClass('hidden')) {
showTable($table);
} else {
hideTable($table);
}
});

jquery.each not working after jquery.load

I use jQuery.load to load the HTML template. After this I'm trying to get HTML content from each loaded HTML element. The HTML is loading but I can't get the HTML content.
Here is the code:
var _InterfaceBuilder = function() {
var k45 = new _K45Kit;
var _this = this;
this.build = function(element) {
var error = false;
switch(element) {
case 'loginPanel':
$('#content').load('template/loginPanel.html', _this.localize(element));
break;
//sth else
}
// sth else
};
this.localize = function(section) {
$(".loginPanel.localString").each(function(index) {
console.log($(this).html());
});
//sth else
});
When I put
$(".loginPanel.localString").each(function(index) {
console.log($(this).html());
});
into the firebug console it works correctly. Can someone help me?
The 2nd parameter for $.load() must be a function that will be called once completion. You are not providing a function, but the result of calling _this.localize(element). So basically, the localize function is called before adding the listener, and since it returns undefined you have no handler.
Try with:
$('#content').load('template/loginPanel.html',
function(){
_this.localize(element);
});

Javascript function only works after page refresh

I have a forum that has a "subscribe" and "unsubscribe" button. When you hit it once, it changes but then doesn't switch back again until the page is refreshed.
http://jsfiddle.net/7QPyL/
Here's my code:
$(document).ready(function () {
// Subscribe to topic subscribedtotopic
$(".notsubscribedtotopic").click(function () {
var topicid = $(this).attr('rel');
$(this).slideUp('fast');
$(this).html('Unsubscribe From Topic');
$(this).removeClass('notsubscribedtotopic').addClass('subscribedtotopic');
$(this).slideDown();
$.get("/base/Solution/SubScribeToTopic/" + topicid + ".aspx",
function (data) {
var result = $('value', data).text();
});
return false;
});
// UnSubscribe to topic subscribedtotopic
$(".subscribedtotopic").click(function () {
var topicid = $(this).attr('rel');
$(this).slideUp('fast');
$(this).html('Subscribe To Topic');
$(this).removeClass('subscribedtotopic').addClass('notsubscribedtotopic');
$(this).slideDown();
$.get("/base/Solution/UnSubScribeToTopic/" + topicid + ".aspx",
function (data) {
var result = $('value', data).text();
});
return false;
});
});
It does not work because the class is not there when you add the event handler, so it can not find the element.
$(".notsubscribedtotopic") and $(".subscribedtotopic") do not magically select new elements as they are added to the page.
You should write one function and just toggle the state.
$(".subscribe").click(function () {
var link = $(this);
var isSubscribbed = link.hasClass("subscribedtotopic");
link.toggleClass("subscribedtotopic notsubscribedtotopic");
...
});
I would set up your code to be something like this:
$(document).ready(function () {
// Subscribe to topic subscribedtotopic
function subscribetotopic() {
var topicid = $(this).attr('rel');
$(this).slideUp('fast');
$(this).html('Unsubscribe From Topic');
$(this).removeClass('notsubscribedtotopic').addClass('subscribedtotopic');
$(this).slideDown();
$.get("/base/Solution/SubScribeToTopic/" + topicid + ".aspx",
function (data) {
var result = $('value', data).text();
});
return false;
}
// UnSubscribe to topic subscribedtotopic
function unsubscribetotopic() {
var topicid = $(this).attr('rel');
$(this).slideUp('fast');
$(this).html('Subscribe To Topic');
$(this).removeClass('subscribedtotopic').addClass('notsubscribedtotopic');
$(this).slideDown();
$.get("/base/Solution/UnSubScribeToTopic/" + topicid + ".aspx",
function (data) {
var result = $('value', data).text();
});
return false;
}
});
And then make a simple onclick call in your HTML element, like so:
<button onclick="subscribetotopic()">Subscribe</button>
If you'd prefer to keep your code the way it is, then clarify which element you want to have active.
Example (simply set a div w/ id mymainelement and button w/ id subscribebutton):
$(#mymainelement .subscribebutton).click(function() { ... });
If you'd prefer to toggle the button instead of having two separate elements, check out #epsacarello's answer.

how to fix my JQuery bug?

The script is on jsfiddle here : CODE
What it does at the moment: it's a form that have two types of URL field textarea and input, it converts the texts in those fields to a link to be click-able.
How it works: if you click next to the link/links you can edit the link or on a double click on the link. IF you click once on the link it takes you to that page.
Last update: i added the .trigger('blur'); on the last line, Because before i did that, the text area was showing the links like one merged link, for example : test.com and test2.com were showing test.comtest2.com, after i added this last update, the split for textera work also on the load of page not just on the edit of textarea ( it was working without the last update but only when you edit the textarea and put between links a space, and i want it to be working on the load of page because the textarea format was sent already as one link pre row ).
My problem: after i did this last update, the double click is messed up, it should just be able to edit the link and don't go to that page unless one click, but now it edits it and in like one second it goes also to that page. I want the double click just to edit without going to that page. and to go only with one click.
Thanks a lot in advance!
The code also here:
$('.a0 a').click(function(){
var href = $(this).attr('href');
// Redirect only after 500 milliseconds
if (!$(this).data('timer')) {
$(this).data('timer', setTimeout(function () {
window.open(href, '_blank')
}, 500));
}
return false; // Prevent default action (redirecting)});
$('.a0').dblclick(function(){
clearTimeout($(this).find('a').data('timer'));
$(this).find('a').data('timer', null);
$(this).parent().find('input,textarea').val($(this).find('a').text()).show().focus();
$(this).hide();})
$('.a0').click(function(){
$(this).parent().find('input,textarea').val($.map($(this).find('a'),function(el){return $(el).text();}).join(" ")).show().focus();
$(this).hide();})
$('#url0, #url1,#url4').each(
function(index, element){
$(element).blur(function(){
var vals = this.value.split(/\s+/),
$container = $(this).hide().prev().show().empty();
$.each(vals, function(i, val) {
if (i > 0) $("<span><br /></span>").appendTo($container);
$("<a />").html(val).attr('href',/^https?:\/\//.test(val) ? val : 'http://' + val).appendTo($container);;
}); })
}).trigger('blur');
A double-click is always predeeded by the following chain of events:
mousedown, mouseup, click, mousedown, mouseup, click, dblclick
You can make your click-events wait and check if a double-click event happened afterwards. setTimeout is your friend. Be sure to copy any data you need from the event object passed to your handler. That object is destroyed after the handler finished - which is before your delayed handler is invoked.
You can manually dispatch a double click event to prevent click-events from being executed prior to them. See the Fiddle
// ms to wait for a doubleclick
var doubleClickThreshold = 300;
// timeout container
var clickTimeout;
$('#test').on('click', function(e) {
var that = this;
var event;
if (clickTimeout) {
try {
clearTimeout(clickTimeout);
} catch(x) {};
clickTimeout = null;
handleDoubleClick.call(that, e);
return;
}
// the original event object is destroyed after the handler finished
// so we'll just copy over the data we might need. Skip this, if you
// don't access the event object at all.
event = $.extend(true, {}, e);
// delay click event
clickTimeout = setTimeout(function() {
clickTimeout = null;
handleClick.call(that, event);
}, doubleClickThreshold);
});
function handleClick(e) {
// Note that you cannot use event.stopPropagation(); et al,
// they wouldn't have any effect, since the actual event handler
// has already returned
console.log("click", this, e);
alert("click");
}
function handleDoubleClick(e) {
// this handler executes synchronously with the actual event handler,
// so event.stopPropagation(); et al can be used!
console.log("doubleclick", this, e);
alert("doubleclick");
}
jsfiddle refuses to load on my connection for some reason, so cant see the code.
Based on your explanation i suggest you look into event.preventDefault to add more control on what should happen on your click events. This could be used in conjunction with #rodneyrehm's answer.
Refer to my previous answer.
For your quick reference, I have pasted my answer here
$('.a0 a').click(function(){
var href = $(this).attr('href');
// Redirect only after 500 milliseconds
if (!$(this).data('timer')) {
$(this).data('timer', setTimeout(function() {
window.open(href, '_blank')
}, 500));
}
return false; // Prevent default action (redirecting)
});
$('.a0').dblclick(function(){
var txt = document.createElement('div');
$.each($(this).find('a'), function(i, val) {
clearTimeout($(val).data('timer'));
$(val).data('timer', null);
$(txt).append($(val).text());
$("<br>").appendTo(txt);
});
var content = $(this).parent().find('input,textarea');
var text = "";
$.each($(txt).html().split("<br>"), function(i, val) {
if (val != "")
text += val + "\n";
});
$(content).html(text);
$(this).hide();
$(content).show().focus();
})
$('#url0, #url1, #url4').each(function(index, element) {
$(element).blur(function(){
if ($(this).val().length == 0)
$(this).show();
else
{
var ele = this;
var lines = $(ele).val().split("\n");
var divEle = $(ele).hide().prev().show().empty();
$.each(lines, function(i, val) {
$("<a />").html(val).attr({
'href': val,
'target': '_blank'}).appendTo(divEle);
$("<br/>").appendTo(divEle);
});
}
});
});
​

Categories

Resources