This question already has answers here:
jQuery onclick all images in body
(3 answers)
Closed 5 years ago.
Is it possible to write a JQUERY event that if any image is clicked on, a message box gets displayed. Or does every image have to have its own event to activate. I know how to specific images but is it possible to have one JQUERY for all images?
Use generic html tag in jquery selector, like:
$("img").click(function() {
//DoForAllImgs();
});
Yes.you can trigger by tag name like
$('img').on('click',function(){
alert($(this).attr('src'));
//alert('any one image clicked');
});
You can use event delegation thus event will be added to one element and delegated to decendent image children
Event delegation allows us to attach a single event listener, to a
parent element, that will fire for all descendants matching a
selector, whether those descendants exist now or are added in the
future.
$(document).on('click','img',function(){
//Your handler
});
Instead of document you may use any container inside which you want to delegate click event on image.
This technique will fire click event on dynamically add image also.
You can place a listener on the whole document and specify a selector, in this case 'img':
$(document).on('click', 'img', function (e) {
console.log('click');
});
This will make any current or future img that is inserted into the DOM clickable.
Related
This question already has answers here:
Click event doesn't work on dynamically generated elements [duplicate]
(20 answers)
Closed 7 years ago.
Here's a simplified version of my jQuery script that I cannot force to work properly.
http://jsfiddle.net/qk2nupq6/ (code's also below)
There's a "#press" div within a "#container". After pressing "#press", the content of "#container" is changed via .html() but the "#press" is still there so that is can be pressed again and the function can be run again.
For some reason, after pressing the button once, the function does not run again and I do not really have any clue why is that so.
HTML
<div id="container">
<div id="press">press </div>
</div>
JS
$(document).ready(function(){
$("#press").click(function(e){
console.log("x");
$("#container").html($("#container").html()+"<div>added</div>");
})
})
When you replace the innerHTML of the element the events bound to the elements are removed. So, when you replace the HTML even with the same content, previously bound events will not work.
Use event delegation
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
Use on to bind event
$('#container').on('click', '#press', function() {
Demo
$(document).ready(function() {
$("#container").on('click', "#press", function(e) {
$("#container").html($("#container").html() + "<div>added</div>");
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div id="container">
<div id="press">press</div>
</div>
You can use .append() like this:
$(document).ready(function(){
$("#press").on('click', function(e){
console.log("x");
$("#container").append("<div>added</div>");
})
})
Here is the FIDDLE.
Explanation:
You were replacing the html of the element so, any event bound to it
were removed.
Use Event Delegation:
Event delegation refers to the process of using event propagation
(bubbling) to handle events at a higher level in the DOM than the
element on which the event originated. It allows us to attach a single
event listener for elements that exist now or in the future. Inside
the Event Handling Function.
Or Append new data to existing element
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 7 years ago.
For example : When click on the aaa button, 'bbb' button is inserted but later when click on the bbb button i dont have allert. Why ?
<button id="aaaa">aaaa</button>
<div id="abc"></div>
<script>
$("#aaaa").click(function() {
$("#abc").html('<button id="bbb">bbb</button>');
});
$("#bbb").click(function() {
alert("sasasa");
});
</script>
Basically your $("#bbb") returns no matches, so does not register the click event at all. That element only exists later.
As the item is added dynamically, you need to use a delegated event handler, attached to a non-changing ancestor of the element:
e.g.
$(document).on('click', "#bbb", function() {
alert("sasasa");
});
This version of on applies the jQuery selector at event time, so the element does not need to exist until event time (rather than when the event was registered).
document is the default if nothing else is closer/convenient. Do not use body as it has a bug (to do with styling). In your example you probably want to attach to '#abc'.
e.g.
$('#abc').on('click', "#bbb", function() {
alert("sasasa");
});
Use this code:
$("#abc").on(click,'#bbb',function() {
alert("sasasa");
});
cause you need to use delegated events to use jquery on elements added to a DOM
This question already has answers here:
Events triggered by dynamically generated element are not captured by event handler
(5 answers)
Closed 8 years ago.
So I have a bunch of game pieces that I want to be clickable. If I add a click function to a button I get the desired result, but when I add it to the game piece class, it fails to work.
Here is an example that works fine on jsfiddle, but not when I use it in my script:
http://jsfiddle.net/sLt7C/
Here is what I want to do on my page:
$('.gamePiece').click(function(){
$('.gamePiece').addClass("toggled");
});
This doesn't work, but if I switch the identifier to a button on the page it does work:
$('#btn_AddClass').click(function(){
$('.gamePiece').addClass("toggled");
});
What could be causing this to fail?
Not sure if this has any impact on what could be causing it to fail, but the "game pieces" are span elements that are generated after clicking a "New Game" button.
Here is a fiddle showing more code http://jsfiddle.net/sLt7C/4/
For further clarification:
This doesnt work
$('.gamePeice').click(function(){
$(this).addClass("toggled");
});
This works
$('#btn_addClass').click(function(){
$('.gamePeice').addClass("toggled");
});
If the game pieces are added after the page load (i.e. by clicking a button) you need to use event delegation by using jquery .on()
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
$(myContainer).on('click', '.gamePiece', function(){
$(this).addClass("toggled");
});
I think you want this:
$(document).ready(function() {
$(document).on('click', '.gamePeice', function(){
$(this).addClass("toggled");
});
});
instead of
$('.gamePeice').click(function(){
$(this).addClass("toggled");
});
$('#btn_addClass').click(function(){
$('.gamePeice').addClass("toggled");
});
just prove http://jsfiddle.net/aras7/sLt7C/7/
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 9 years ago.
How do you hook into javascript / popup functionality that is invoked after a user clicks?
We have javascript code that gets invoked by a user click. This javascript code renders a popup dialog that contains an choose file tag. This choose file tag is literally appended by doing something like:
output.append('<input type="file" ......'>
So the problem with this is if the user doesn't first click this tag never gets rendered in the response.
We are currently using a jQuery $() function to execute our code that looks for tags as soon as the web page loads, however our $() function does not get called when the user clicks the link rendering the popup.
Is there another hook we can use in jQuery besides $() that gets invoked when a popup gets rendered?
If I understand correctly, you want to attach an event handler at page load time to an input that will not exist until the user clicks a link. One solution is to use event delegation. You can look for "delegated events" in the documentation for the .on() function.
Basically, you call .on() on an element that already exists in the DOM that is an ancestor of the element that will be added later. You supply a selector as the second parameter that identifies the element you want the handler to execute for.
You could use:
$(document).ready(function() {
$(document.body).on('click', 'input:file', function() {
...
});
});
But it is more efficient to use a closer ancestor than the <body> element if you can, and you might have a better selector for identifying the file input element than the one I show above (since it will match all file input elements).
Either create proper elements with event handlers :
var file_input = $('<input />', {
type : 'file',
on : {
change : function() {
// do stuff
}
}
});
output.append(file_input);
or use a delegated event handler
output.on('change', '.file_input', function() {
// do stuff
});
output.append('<input type="file" class="file_input" ......'>
Of course it is possible. You have to define your function for the later rendered element after it is rendered.
HTML:
<div id="holder">
<button id='first'>first</button>
</div>
JQuery:
$('#first').click(function () {
alert('first click');
$('#holder').append("<input id='second' type='file' name='pic' accept='image/*'>");
$('#second').click(function () {
alert('second click');
});
});
Here is a demo: JSFIDDLE
I'm trying to prevent an event on dynamically created elements.
I tried several ways but none worked.
On deafult, a click on the div containing the class opens a menu, and I want to disable that.
This is my code (please note I'm using jQuery 1.6.4 so I'm not able to use the "on" method).
$(function() {
$( document ).delegate( "span.highlight_mkt", "click", function() {
return false;
});
});
I have tried this using the "live" method as well but without any success.
Any help would be much appreciated.
maybe this link helps you -> preventDefault
$(document).delegate("span.highlight_mkt", "click", function (e) {
e.preventDefault();
/* your code here */
});
EDIT
you tried this too?
$('span.highlight_mkt').live("click", function (e) {
e.preventDefault();
/* your code here */
});
This one should stops the event propagation:
$(function() {
$( document ).delegate( "span.highlight_mkt", "click", function(e) {
e.preventDefault();
e.stopPropagation();
return false;
});
});
What I understand from your question is you have span with highlight_mkt class in your html form with click event attached using selector or document. And you are loading using Ajax or dynamically creating other span with same class name.
So in order to prevent events on your dynamically created elements you can use .die() function with container name where you are attaching dynamically created elements as following:
$('container_selector span.highligh_mkt').die('click');
In this method click event will be fired only your elements which is not attached dynamically.
If I understand you incorrectly please clarify your question.
What you did is you are attached event handler to document element or global container using .live() jquery function. So it is not good thing to do. I will explain later.
$('body').live('click','span.hihligh_mkt', function(e){
//Your code here. Which is doing some cool staff i believe :)
});
However if you want to prevent only for dynamically created elements do following:
$('body').live('click', 'span.some_class', function(e){
// This part is needed in order to check weather it is attached dynamically
// or it is predefined html objects
if($(e.target).closest('#some_container').length==0)
{
//Your code here. Which is doing some cool staff i believe :)
}
});
So in above you will just check, does event fairing element is dynamically attached to container element or it is part original html. Of course this kind of method can be avoided if you will use event which will be attached individually to the the elements like following when DOM ready.
$('span.hihligh_mkt').live('click', funtion(e){});
In this case only elements which was exists in DOM ready will get handlers. Other dynamically attached elements will not have event handlers. Unless you are not doing deep cloning of span elements.
Another thing is here when you attaching event handler to body or other root elements it gives you slow performance. You can read about it here.
Since all .live() events are attached at the document element, events
take the longest and slowest possible path before they are handled.
You can see some example here.