Jquery .click() not work if HTML element not yet added - javascript

I tried method :
Attaching click event to a JQuery object not yet added to the DOM
but seems not working in my situation. After I created dom elements by jquery, the newly created elements are not accessible. What I want is to after clicking "click me" button, and the image will show up and I hope click the image and a div (#color-picker-box) to show up.
My code: https://codepen.io/MoMoWongHK/pen/ZXbWYb

add the number sign # when calling the id of your div,
from
$("myDiv").on("click" ,".color-picker-icon" , function(){
alert("hi");
$("#color-picker-box").removeClass("display-none");
});
to
$("#myDiv").on("click" ,".color-picker-icon" , function(){
alert("hi");
$("#color-picker-box").removeClass("display-none");
});

You just missed # while using myDiv as a selector!
Wrong:
$("myDiv").cl....
Corrected:
$("#myDiv").cl.....

You need to use event Delegation since the element is not added to dom yet. You need to capture the click on its parent.
$('#myDiv').on("click", "#color-picker-box", function(e){
console.log('color box clicked');
});
Read more about it on:
https://learn.jquery.com/events/event-delegation/
http://api.jquery.com/on/

Related

Simulate a click on js

I have a problem on my website. I have a <div id="test"> which is display:none by default.
Now, when I click on the button it changes to display:block, but in my div a popup is displayed which disappears when I make a click.
So I need to simulate a click so that the another div does not show.
I tried :
<script>
document.getElementById('test').setAttribute('class','display-block');
document.getElementById('test').click();
</script>
But it does not work.
// element you click to execute the display
$('#button').on('click', function(){
$('#test').css('display','block');
});
Use jQuery .trigger()
http://api.jquery.com/trigger/
$('#test').trigger('click');
document.getElementById('test') returns a plain DOM node which doesn't do much. If you use $('#test') you will get the same DOM node, but wrapped in jQuery.
jQuery provides a .click() function on these "wrapped" nodes, which will simulate a click on the button for you:
$('#test').click();
(which is just a shortcut for .trigger('click') - read more here)
is the same as
$(document.getElementById('test')).click();
You can use jquery to do it:
$('#test').click()
or
$('#test').trigger("click");
Check the demo here: http://jsfiddle.net/eq9c2p2c/
update
You need to add click event, then you just trigger it.
This is the HTML:
<div id="test">click</div>
Javascript:
$('#test').click(function() {
$(this).addClass("border")
})
$('#test').click()
http://jsfiddle.net/eq9c2p2c/2/

Javascript, Jquery ,DOM

After appending a button on Html document the jQuery event associated with it not working ?
For example:
$("#mydiv").append('X');//this is button appending
$("#mybutton").click(function(){
alert("hello");
});
Assuming you call the .click() method on #mybutton before it is actually appended to #mydiv, you need to use .on() as the button doesn't exist when you attach the event handler:
$('#mydiv').on('click','#mybutton',function(){
alert('hello');
});
Should work...
Why don't you set the click inside the append?
This way you wouldn't need to concern about the element being added or not to the document's flow, since you'd be setting the event callback on the actual DOM element variable:
$("#mydiv").append(
$('X').click(function() {
alert("hello");
})
);

jQuery prevent function to duplicate on click

I want to initiate a plugin only if clicked on its parent element (because that element is being appended with jQuery so it does not exist when page loads), So I am trying following code:
$(document).on('click', '.wrap', function(){
ColorPicker(
document.getElementById('slider'),
document.getElementById('picker'),
function(hex, hsv, rgb) {
});
});
This works fine, but every time I click on the .wrap, it duplicates (please check the demo to see the problem). Is there anyway to fix it?
Demo:
http://jsfiddle.net/rhzzG/
(Click in the box to see the problem)
Thanks.
Rather than using on() to trigger this event every time the element is clicked, simply use jQuery's one() method to only fire it once:
$(document).one('click', '.wrap', function(){ ... });
ColorPicker will then take over from there with handling its own events.
JSFiddle demo.
You may use one instead
$(document).one('click', '.wrap', function(){
//...
});

Registering an existing event to ajax loaded DOM?

In my homepage , I have this button.
<button class="test">test</button>
And in my current code I have this script
$('.test').on('click',function(){
alert("YOU CLICKED ME");
});
Now, my application is ajaxified, so everytime I click a new page it is loaded as ajax, the problem is that the loaded page also has this button. and its markup is likethis
<div id ="firstDiv>
<div id ="secondDiv">
<button class="test">test</button>
</div>
</div
So the new content also has "#test" but how come when I click that button it does not execute the event handler I created?
var $bdy=$(document.body);
$bdy.on('click','.test',function(){
alert("YOU CLICKED ME");
});
now append your .test anytime you like
So the new content also has "#test" but how come when I click that button it does not execute the event handler I created?
Because the handler is attached to the actual element. So if the element is removed and a new element with the same class is created, the event is not associated with that new element.
You could use event delegation to handle this:
$(document.body).delegate('.test', 'click', function(){
alert("YOU CLICKED ME");
});
or
$(document.body).on('click', '.test', function(){
alert("YOU CLICKED ME");
});
(They do the same thing, note the order of arguments is different. I prefer delegate for the clarity, but I think most people use the delegating version of the far-too-overloaded on method instead.)
What that does is watch for the click on document.body, but only fire your handler if the click passed through an element matching that selector (.test, in this case).
As you said that the content is loaded through data you get in AJAX this is the possible scenario that is happening.
<button class="test">test</button> is drawn
Then it is binded to to click event
You load the new data through ajax
Try to bind that it does not.
This is because when you first bind the click event to "test" element with that class are part of the DOM. Now that you add some markup after ajax call the elements become the part of DOM, but now after you wrote the new markup you need to first unbind the click event See Here. And then re-bind the click event. This will bind the event to all elements having class "test".
P.S. I don't know the specifications of your implementation but as others have suggested you should bind events to id and not class.
I finally found out the solution. all I needed to do was define a static container which is this
$('#staticdiv').on('click','.test',function(){
alert("YOU CLICKED ME");
});
and that fixed the issue

Later-inserted tags not seen by JQuery

Say I have this code in my page:
<script language="javascript">
$(document).ready(function() {
$(".test").click(function() {
alert('Hello');
});
});
</script>
Why doesn't the previous code apply to elements with the class "test" which I add later to the document like this for example:
$('body').append('<p class="test">Test</p>');
Because what happens is that when I click the previous <p> tag nothing happens.
Also, if I have this:
<div id="first">Edit me.<div id="second">Save me.</div></div>
Can I do what the text describes? that is, controlling the content of the #first div without affecting the content of the #second div?
Thank you.
The problem is that .click() does only apply a listener for elements that are available in the DOM when the method is executed. You should take a look at .on() instead.
With .on() you can delegate the event, like this for instance:
$("body").on("click", ".test", function() {
alert('Hello');
});
Now any element (current and future) with the class test available within your body will have a click-event listener.
live is deprecated as of 1.7, use on
http://api.jquery.com/on/
try using on() listener:
$(document).on("click",".test", function() {
alert('Hello');
});
When you bind events to elements they only bind to those elements that have already been created. So you need to run the 'bind' command again on the new elements.
Alternatively, you can use on('click') which will bind the event to existing and all future elements.
Because at the time you attach your event handler the object doesnt exist yet. You cant subscribe to elements that dont exist. You can use the Live method for this.
http://api.jquery.com/live/
It seems those are deprecated (thanks #Anthony Grist). Use On, or delegate() instead.
http://api.jquery.com/on/
http://api.jquery.com/delegate/
$('div').on('click', function()
{
//Do something
});
you should use "on" to bind events with the elements that are added after the script is interpreted.
$(document).on("click", selector, function(e){
//do something
});
If you need to apply the click to later added tags, you should use live on
$(document).on('click','.test',function() { });
EDIT: #Anthony your're right. live is deprecated. Updated the code

Categories