Theres a gap in my understanding that i'd liked filled;
I have a basic jQuery click function like this..
$('.cl').each(function(e)
{
alert('works');
$(this).click(function()
{
alert('no works');
});
});
My HTML is like this:
<body>
<div id='c0'>
<div class='bO cl'>Button</div>
</div>
</body>
Basic stuff.
The 'works' alert is fired ok - but with the click function nothing happens - 'no works' is not fired.
Also
$('.cl').click(function()
{
alert('help');
});
Does not work. Simple stuff i'm sure but i'm missing something.
Why is this?
One thing to make sure is that you run the event handler once the DOM and jQuery are initialized, which is by doing this:
$(function() {
$('.cl').click(function()
{
alert('help');
});
});
Also alternatively, if your cl is loaded after the fact such as by an Ajax call you can alternativley do this
$("body").on("click", ".cl", function() {
// Your code here
})
This registers the click event with the body but only gets dispatched if the actual target is of type cl.
Related
I have a DIV that is in an .html file that is loaded into my document via:
$(document).Ready( function() {
$("#contentDiv").load("some.html")
//some.html contains a button id=saveButton
$("#saveButton").click( function () {
alert("Here I am!");
}
});
The event will not fire. If I cut the content of some.html and put it in the document, uhm, "physically", the event will fire.
So, I am pretty sure this issue is related to the fact that the html is injected via .load().
It's bothersome, because if you look at the page source, all the HTML is in fact there, including the button.
So, the question is, is there ANY way to make this work? I am using .load() to reduce page complexity and increase readability, and, code-folding notwithstanding, I really do not want to have to pull all this HTML into the document.
EDIT: This code was just typed in off the cuff. It's not a cut-n-past of the actual code, and it is just to demonstrate what the problem is. But, thanks for pointing it out.
EDIT2: Grrrrrrr. });
load() is asynchronus so you need to the job in the callback :
$(document).ready(function() {
$("#contentDiv").load("some.html", function(){
//some.html contains a button id=saveButton
$("#saveButton").click( function () {
alert("Here I am!");
});
});
});
Hope it helps :)
one way is by adding to the some.html the script line which will be loaded as the div appears.
You can add this script to some.html(in a script tag):
registerButton();
and then you can define registerButton() in your current document.
other way, if I remember correctly is by using something like the function bind( )
If you want to fire event on element which was not available at the time when DOM was ready then you need to use .on event.
http://api.jquery.com/on/
$("#saveButton").on("click", function() {
alert("Here I am!");
});
jquery load() function is asynchronous. If you want to bind events to the loaded content, you should put the code into the callback function:
$(document).ready(function() {
$("#contentDiv").load("some.html", function() {
//you should put here your event handler
});
});
Your issue is that jquery load() function is asynchronous as #lucas mention. But his code has syntax errors, try this:
$(document).ready(function () {
$("#contentDiv").load("some.html", function () {
$("#saveButton").click(function () {
alert("Here I am!");
});
});
});
Hope it helps now
You need to bind the event handler either after the load OR to the container of the HTML from the load
$(document).ready(function() {
$("#contentDiv").load("some.html", function() {
$("#saveButton").on('click',function() {
alert("Here I am! Bound in callback");
});
});
});
OR use: (not needed that it be in the document ready just that the contentDiv be present)
$("#contentDiv").on('click','#saveButton',function(){
alert("Here I am! bound to container div");
});
EDIT: load on the SAVE button click (per comments) (this makes no sense though)
$(document).ready(function() {
$("#saveButton").on('click',function() {
$("#contentDiv").load("some.html", function() {
alert("Here I am! Bound in callback");
});
});
});
Say I have a simple button like:
<button id='test'>ClickME</button>
on which through some script (provided by some other person), a click event is registered, like this:
$('#test').on('click', function(){
alert('click 1'); //Some lines of code
});
Later on the page load, I ran my script on top of it, in which I wanted to perform some actions on the same button click. In the script, I wrote something like:
$('#test').on('click', function(){
alert('click 2'); //Some lines of code
});
In this case, when I click on the button, I am getting two alerts which is understandable.
What I wanted to achieve is, First "click 2" should be alerted and in the same code, based on some condition, I may or may not call the previously registered function, i.e. "click 1" alert. I have no clue whether we can achieve such things and if yes, how can I prevent execution of already registered event?
Any help is appreciated.
You can unbind all previous event handlers from an element. Before that, you can store what they were. This allows you to write code like:
// not your code
$('#test').on('click', function(){
alert('click 1'); //Some lines of code
});
// your code
var prevHandler = $._data($("#test")[0], "events").click[0].handler;
$('#test').off('click');
$('#test').on('click', function(){
alert('click 2'); //Some lines of code
if (Math.random() > 0.5)
prevHandler();
});
jsfiddle: https://jsfiddle.net/ugefofLs/
Both handlers will run, the jQuery event model allows multiple handlers on one element, therefore a later handler does not override an older handler.
The handlers will execute in the order in which they were bound.
I suggest you merge the two code block something like this:
$('#test').on('click', function(){
alert('click 2'); //Some lines of code
if (some condition){
alert('click 1'); //Some lines of code
}
});
If you do not know whether or not other events have been registered, and still want to make sure only your event fires, you can use jQuerys event.stopImmediatePropagation() to only allow your event to be run.
event.stopImmediatePropagation()
Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree.Keeps the rest of the handlers from
See the code and snippet below
//Change this to false to let both registrered events run
var preventOtherClickEvents = true;
var onClick = function(event) {
if (preventOtherClickEvents) {
event.stopImmediatePropagation();
}
alert('First event handler');
};
var onClickSecond = function() {
alert('Second event handler');
};
$('#button').on('click', onClick);
$('#button').on('click', onClickSecond);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="button" value="Click Me" />
I need to check if user closed browser. There is no reliable way, but the most accurate way seems to use onbeforeunload and check if a link or a button was clicked. I will also add f5 and some other extra checking.
But I have problem with button. If I click button, ajax call will be made even if there is if(window.link_was_clicked==false) condition.
<button onclick="setLocation('http://dev.site.com/checkout/')" class="button" title="Checkout" type="button"><span><span>Checkout</span></span></button>
And script:
jQuery(document).on('click', 'button', function(event) {
window.link_was_clicked= true;
});
window.onbeforeunload = function() {
if(window.link_was_clicked==false){
//make ajax call
}
};
It seems the problem is because there is setLocation function attached to button onclick. Is there any way to trigger jQuery(document).on first?
That variable doesnt exist on before load. so add it on the top and try again
window.link_was_clicked=window.link_was_clicked||false;
jQuery(document).on('click', 'button', function(event) {
window.link_was_clicked= true;
});
window.onbeforeunload = function() {
if(window.link_was_clicked==false){
//make ajax call
}
};
Since you haven't provided the code for setLocation(), I'll assume that that's where the problem is. Now, regarding a change to the order of execution of your click event handlers:
It is in general bad to have both embedded onclick and jquery-bound handlers, it leads to all sorts of confusion. If you can't change the html, however, you could do what this guy suggests: https://stackoverflow.com/a/7507888/2685386
$(document).ready(function() {
var myClick = $('button').attr('onclick');
$('button').removeAttr('onclick');
$(document).on('click', 'button', function(e) {
window.link_was_clicked=true;
// do my other stuff here....
eval(myClick);// this will now call setLocation()
});
});
I'm using a popover in bootstrap, and I want it to close when the user clicks anywhere else on the screen. The code I have is this:
$('#popover').bind('click', function() {
$(".popover").live('click', function(){ return false; });
$(document).one("click", function() {
alert('click');
});
});
The problem is that the click on the button is triggering the alert. For some reason javascript uses that click to start the function and trigger the click event inside of it. What am I doing wrong?
EDITED:
This code doesn't do anything:
$(".popover").live('clickoutside', function(){
alert('click');
});
Check out these:
https://developer.mozilla.org/en-US/docs/DOM/event.stopPropagation
https://developer.mozilla.org/en-US/docs/DOM/event.stopImmediatePropagation
If your .popover is inside #popover, you're triggering events from all the affected elements.
NOTE: jQuery's live is in deprecating process, use the alternatives:
http://api.jquery.com/on/
http://api.jquery.com/delegate/
I have a case where a click handler is defined/assigned in one jQuery code block (file) and I want to trigger it from another click event defined/assigned in a different jQuery code block. How can I accomplish this?
The following code is a greatly simplified version of what I am trying to accomplish. The behavior I want to see is a JavaScript alert "Element One" when I click #Element2.
Example HTML:
<p id="Element1">Element One</p>
<p id="Element2">Element Two</p>
First jQuery code block:
$(document).ready(function() {
$('#Element1').click(function() {
alert('Element One');
});
});
Second jQuery code block:
$(document).ready(function() {
$('#Element2').click(function() {
$('#Element1').click();
});
});
UPDATE: My original example actually works. I was building upon my field hint jQuery UI Dialog solution, and didn't account for about the 'clickoutside' handler that I was using. Adding a check to for the second element in my 'clickoutside' handler allows the dialog to display.
You need to trigger a click when you click on the first element. You can use the trigger method for this.
function element1Hanlder () {
alert('Element One');
}
$(document).ready(function() {
$('#Element1').click(function() {
alert('Element One');
});
});
$(document).ready(function() {
$('#Element2').click(function() {
$('#Element1').trigger('click');
});
});
EDIT: This is based on JohnP's "trigger" suggestion (so you should choose him as the right answer)...
If I load this block from an external js file...
$(document).ready(function() {
$('#Element1').click(function () {
alert( $(this).text() );
});
});
Then load this in a script tag within the HTML itself...
$(document).ready(function() {
$('#Element2').click(function () {
$('#Element1').trigger('click');
});
});
Seems to be working as intended.