I have a function:
function test(e){
$('.movie').find('.moreInfo').removeClass('moreInfoShow');
e.parent().find('.moreInfo').addClass('moreInfoShow');
$("#movieBox").isotope('reLayout');
e.parent().find('.moreInfo').css("opacity", "0");
e.parent().find('.moreInfo').animate({opacity: 1}, 500);
}
which is called by:
$("#movieBox").on('mouseover', '.moviePoster', function(event){test($(this));});
The issue is that I want the function to be called when the page loads. I need to pass "this" to the function but I have had no luck in getting it to work.
This is what I expected to work:
test($(".moviePoster").first());
(ALL code is in "$(document).ready" function)
W/O fiddle:
Change this:
$("#movieBox").on('mouseover', '.moviePoster', function(event){test($(this));});
to
$("#movieBox").on('mouseover', '.moviePoster', test);
Then $(this) inside test function should point to the jQuery object which triggered the event.
Invoking test function in the callback with "test($(this))" will instantly execute the function and not when the event is fired.
Update:
After you did this, you'll need to trigger the mouseover event on page load of course.
See Jashwant's comment on how to do that.
Update I was wrong.
function(event){test($(this));}
will of course not trigger the callback function instantly. This only would happen if it would be like this:
$("#movieBox").on('mouseover', '.moviePoster', test($(this)));
Sorry!
As stated in comments, trigger the mouseover event on page load.
$("#movieBox").find('.moviePoster').trigger('mouseover');
Reference
Related
I just got through figuring out that I need to watch out for duplicate event handlers in jquery if I'm dynamically assigning them multiple times as described here: http://www.parallaxinfotech.com/blog/preventing-duplicate-jquery-click-events
Do I need to watch out for this or handle it somehow if I'm declaring a function dynamically within another function multiple times? How does JavaScript really handle this? Does it only use the last function that was called or does it only instantiate a function once at load time? From what I can tell it's not running the function multiple times.
$(document).on("click",".button",function() {
function alertThem()
{
alert('Clicked!');
}
alertThem();
});
JavaScript will remember every function you're assigning it.
$('button').click(function(){
alert('hi')
})
$('button').click(function(){
alert('hi')
})
The code above will alert "hi" twice. If you're assign new function and you want to clear the old one, you can do unbind().click(). what it will do is it will unbind all events, or you can do unbind('click') which will unbind just the click. see https://jsfiddle.net/rznbtc1p/
$('button').click(function(){
alert('hi')
})
$('button').unbind().click(function(){
alert('hi')
})
The link you provided does not work (gives me timeout) so I hope I understood what you asked.
About what happens there:
In your script you created a closure and bound it to a click event. Each time you click on the element with class button, the anonymous function is triggered. Each time is triggered it defines function alertThem(), and calls it. Only once defines it, only once calls it. The scope of that function is its parent, the closure. That function is not defined outside that scope, so no need to worry about double definition.
Side note here: Personally as a rule of thumb don't think is a good idea to define functions like this, but if it suits your project... go for it.
Now about duplication. Since I cannot see the link, I think you are referring to double event binding.
In js can bind any number of events to the same element. You can for example bind on click something that says "Hi, you clicked me", then bind also on click something that says "Hi, you received a message before saying you clicked me". When you click that element, you will see both messages.
This can actually become a problem. You have 3 options:
Be really careful how you bind events
Keep tracking of what you bound
Check if events are already bound (although that is a bit unreliable). You can check how here: jQuery find events handlers registered with an object
In your code snippet, you aren't creating duplicate event handlers.
What is happening in your snippet is that you are creating a new function alertThem within the scope of your click handler function and then executing it in the line below.
Explaining by example:
$(".myCheckboxes").click(function () {
...
});
Inside the click event function I have code that does various things depending on what checkboxes are checked.
I however need to run this code to initialize it first, kindof like this:
$(".myCheckboxes").click(function () {
...
}).click();
It runs the code and it gets initialized, but it also clicks on all my checkboxes making them all invert their value.
Is it possible to execute the inline click event function wihtout executing a click event?
I would very much like to keep the function inline to keep the flow of the code. Also, it's not big enough to have the function outside of the event, but it's not so small as I would like to write the code twice.
triggerHandler triggers only the handler:
$(".myCheckboxes").click(function () {
...
}).each(function(i, checkbox) {
$(checkbox).triggerHandler('click');
}
Note that you need to iterate the checkboxes if you wish to trigger the handler for all of them instead of just the first one:
while .trigger() will operate on all elements matched by the jQuery
object, .triggerHandler() only affects the first matched element.
Use a named function as the handler, bind it and execute it:
$(".myCheckboxes").click(clickHandler);
clickHandler();
You may consider to call the function triggerHandler who seems to do what you need.
$(".myCheckboxes").click(function () {
...
}).triggerHandler('click');
NB: I haven't tested this solution.
I am building something with Jquery, and I am making some Ajax calls. So after my ajax calls, I need to call functions to trace clicks on some elements again. Here an example of such a function:
$(document).ready(function () {
initSomething();
});
function initSomething(){
$('.something').click(function(){
alert('hello');
});
}
And now an ajax function:
$('#AddSomething').click(function(){
$.post('somewhere.php',{data},function(data){
initSomething();
});
});
And the problem is: I feel like when I initSomething(); for the second time, it's like it's readding a click event on the elements already traced by the first initSomething called on document ready.
So I tried something like e.preventDefault and e.preventPropagation(), but it doesn't seem to work, what am I missing?
Thanks for your answers and have a nice day!
EDIT: As saw on the answers, I forgot to say that the Ajax call is inserting new .something elements in the DOM...
EDIT 2: Here a jsfiddle: https://jsfiddle.net/wpsnz7op/
Try .off() api to remove the already attached event and reassign the event like following.
function initSomething(){
$('.something').off('click').click(function(){
alert('hello');
});
}
Hope this helps....
There is no need to rebind clicks from what I can see of the code you have there.
Just do not rebind and you will not have a multiple click issue.
Use event delegation instead of that.
$(document).on('click','.something',function(){
alert('hello');
});
Then there is no need for calling the initSomething(); function after ajax.
I'm creating a simple app using JS/jQuery as a learning exercise and am running into a problem I've encountered before and can't seem to solve. Why, in the following code, is the second click event triggered automatically rather than when I click $('.tweet li a.username')?
$(function(){
setInterval(update, 3000);
$('.showMore').on('click', function() {
moreIndex += 5;
update();
})
$('.tweet li a.username').on('click', alert('hey!'));
});
alert('hey!') is filler for a function I'm still working out. How should this be organized so that the click event triggers when the link is clicked rather than when the page loads? The $('.showMore') event works properly, even if I change the order.
it is because you are invoking the alert function there instead of passing the callback function reference.
In your case you are invoking the alert() function and pass the value returned by the alert as the click event handler.
$('.tweet li a.username').on('click', function(){
alert('hey!')
});
You need to wrap the alert in a callback function, just like the first example:
$('.tweet li a.username').on('click', function() { alert('hey!') });
The .on method is expecting a JavaScript object in that position, a function in particular, which it can execute later. What is happening in your original code is that the JavaScript engine is looking for a function, but sees some other code there instead -- so it executes the code there (activating the alert) in hopes that a useful object will be returned. (When nothing is returned, the JavaScript engine instead assumes that you want null to be executed on a click event, and happily does so.)
I've come across an issue where jQuery events fire twice after $.load() is called. The event handler is placed in the load() callback function, and this seems to be the only place where events fire twice on the script.
I've tried adding event.stopPropogation() and event.preventDefault(), as these seem to be common suggestions with jQuery events firing more than one. I'm not sure if my code is bubbling improperly or what. Any feedback would be helpful.
Here's an extract of some of the code where you see the behavior.
$("div.questions").load("question_source.php #simplified_a", function(){
...
// Line 1
$("#some_id").change(function(){
cantBeNegative(this);
adjusted_gross_income = $(this).val();
console.log(adjusted_gross_income);
// event.stopPropagation();
// event.preventDefault();
});
You can clearly see the event firing twice with the console.log bit I've got in there. Any advice would be appreciated!
EDIT
OK, I checked through everything on the live page based on some of the suggestions, and there's definitely only one <div id="questions"> in existence when the problem is occurring. So, it doesn't appear to be an HTML problem.
I also checked to see if the event was actually being called twice, and as far as I can tell, the event is only being called once.
Now, I added a .on() event attached to the document which is called on the dynamically created elements, and that only fires once. .on() is not called within the .load() callback. Here's an example used on one of the other input boxes on the page which works without any problems:
$(document).on('change', "#SWA_mothers_income", function(){
console.log("mothers income changes from on()");
});
So, that works properly, but when tested on the same input within the .load() callback function, it fires twice, regardless of how it's called. So, it seems to me that it's almost certainly an issue with .load(). I wouldn't exactly call myself an expert in this, so if someone can figure out the issue, I'd love to know the answer. As it stands, I'm going to rewrite this code using .on().
SECOND EDIT
Adding $("#some_id").unbind('change');
before the 'change(function()) bit did the trick!
add this line
$("#some_id").unbind('change');
before
$("#some_id").change(function(){});
I'm not saying this will solve your problems but you need to pass in the event to reference it.
$("#some_id").change(function(event){
cantBeNegative(this);
adjusted_gross_income = $(this).val();
console.log(adjusted_gross_income);
event.stopPropagation();
event.preventDefault();
});
It's possible that you have two divs with a class of 'questions', so you could be binding the change function twice.
If you update your change function to the below, this will unbind the change event before re-adding it. This will make sure you only have the function bound once;
$("#some_id").unbind('change').change(function(event) {
event.preventDefault();
cantBeNegative(this);
adjusted_gross_income = $(this).val();
console.log(adjusted_gross_income);
});