Jquery click event fire twice - javascript

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.

Related

Chain a div click to another with jquery?

Not sure if I'm using the correct lingo,
But I want to click a div and when I do it should cause another to be clicked after.
Ex click div 1 then div 2 gets clicked (but not by user, just by JS)
Is this possible?
There is already a huge function attached to div 2 when clicked, so I need to to link the two if that makes sense. Easier hopefully than sorting through lots of code and trying to add it in.
Any help?
you can use:
$('#div1').click(function(){
$('#div2').trigger('click');
})
You can just call click() on div 2:
$('#div1').click(function(){
//your code
$('#div2').click();
});
$("#div1").click(function() {
// Do stuff...
// Then click the other DIV
$("#div2").click();
}
It is possible, in the click handler for div one call
$("#div2").click();
Yes this is possible creating the function for the click on the 1.
With
$('#iddiv1').click(function(){
//your code
$('#iddiv2').click();
});
Documentation
Yes you can by doing so:
$("#idDiv1").click(function(){
//do what you want
$("#idDiv2").trigger("click");
}
You need to have an onclick event TRIGGER a click on another div.
$('#foo').click(function() {
$('#bar').trigger("click");
});
$('#bar').click(function() {
// Do something
});
$('#div1').click(function() {
$('#div2').click();
});
Edit:
This solves your problem because it attaches a listener to div1 and executes a function whenever div1 is clicked. It just so happens that you want to emit another event for div1, which, in jQuery shorthand, is written with the .click() function.
Giving .click() a function as a parameter sets the callback for the click event, which can manually be called by calling the function without any parameters.

jQuery event firing twice after .load()

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);
});

Passing "this" to .on function doesnt seem to work

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

Is there any way to use javascript (jquery) to make an element behave **exactly** as if it was clicked (a unique situation)

I want to make 'select' element to behave as if it was clicked while i click on a completely different divider. Is it possible to make it act as if it was clicked on when its not??
here is my code
http://jsfiddle.net/fiddlerOnDaRoof/B4JUK/
$(document).ready(function () {
$("#arrow").click(function () {
$("#selectCar").click() // I also tried trigger("click");
});
});
So far it didnt work with either .click();
nor with the .trigger("click");
Update:
From what i currently understand the answer is no, you cannot. Although click duplicates the functionality it will not work for certain examples like this one. If anybody knows why this is please post the answer below and i will accept it as best answer. Preferably please include examples for which it will not work correctly.
You can use the trigger(event) function like ("selector").trigger("click")
You can call the click function without arguments, which triggers an artificial click. E.g.:
$("selector for the element").click();
That will fire jQuery handlers and (I believe) DOM0 handlers as well. I don't think it fires It doesn't fire handlers added via DOM2-style addEventListener/attachEvent calls, as you can see here: Live example | source
jQuery(function($) {
$("#target").click(function() {
display("<code>click</code> received by jQuery handler");
});
document.getElementById("target").onclick = function() {
display("<code>click</code> received by DOM0 handler");
};
document.getElementById("target").addEventListener(
'click',
function() {
display("<code>click</code> received by DOM2 handler");
},
false
);
display("Triggering click");
$("#target").click();
function display(msg) {
$("<p>").html(msg).appendTo(document.body);
}
});
And here's a version (source) using the onclick="..." attribute mechanism for the DOM0 handler; it gets triggered that way too.
Also note that it probably won't perform the default action; for instance this example (source) using a link, the link doesn't get followed.
If you're in control of the handlers attached to the element, this is usually not a great design choice; instead, you'd ideally make the action you want to take a function, and then call that function both when the element is clicked and at any other time you want to take that action. But if you're trying to trigger handlers attached by other code, you can try the simulated click.
Yes.
$('#yourElementID').click();
If you added the event listener with jquery you can use .trigger();
$('#my_element').trigger('click');
Sure, you can trigger a click on something using:
$('#elementID').trigger('click');
Have a look at the documentation here: http://api.jquery.com/trigger/
Seeing you jsfiddle, first learn to use this tool.
You selected MooTools and not jQuery. (updated here)
Now, triggering a "click" event on a select won't do much.
I guess you want the 2nd select to unroll at the same time as the 1st one.
As far as I know, it's not possible.
If not, try the "change" event on select.

how refresh the document ready in jquery

for example if i write this code :
$(document).ready(function(){
$("div#i").click(function(){
alert("ok");
});
});
and the div element with the i id is not found in the page when load , so after i create it with some function ; and i click it , nothing happen , so how i can refresh the ready function in jquery ..
$(document).delegate('div#i','click',function(){});
Use Delegate
Reference
Delegate vs Live
Demo
Look into using .live() : http://api.jquery.com/live/
Take that click event handler out of (document).ready and place it in the function that you've mentioned which creates the ID.
function someFunction()
{
//creates the id, then
$("div#i").click(function(){
alert("ok");
});
}
EDIT:
If this is just one example among many potential event handlers, then wrap them all in a single function, say, bindEvents() and you can call that every time the page is 'dirtied' by an ID creation.
But the other commenters' approach of using .live() will probably be less to maintain, and it's "the JQuery way" if that's a concern for you.

Categories

Resources