Trigger event when dynamically generated image is clicked - javascript

How do I trigger an event when a dynamically generated image is clicked?
<body>
<!-- this img element is dynamically generated after page load -->
<img class="youtube-thumb" src="//i.ytimg.com/vi/x-4KLOsfkHw/hqdefault.jpg">
</body>
I thought this would work:
$('body').delegate('.youtube-thumb').on('click', function(){
console.log('hi')
})
But this triggers the event when I click anywhere in the body. What am I doing wrong?

Your usage of the delegate() method is incorrect, try this:
$('body').delegate('.youtube-thumb', 'click', function(){
console.log('hi')
});
That said, you should be using on() instead as delegate() is considered outdated. Try this:
$('body').on('click', '.youtube-thumb', function(){
console.log('hi')
});

This should be like following. delegate() function is not needed.
$('body').on('click', '.youtube-thumb', function(){
console.log('hi')
})

Related

Trying to write a function from inline javascript

I've got some code from a developer that left our company. He wrote an inline function looking like this:
<button class="xxx" id="MyID" type="button" onclick="javascript: $('#openThis').slideToggle('slow');">btnText</button>
I've tried to remove this and put it in another function to write a callback so I can scroll to the toggled area when it's visible.
$("#MyID").click(function () {
$("#openThis").slideToggle("slow");
});
But I can't seem to get it to work. What am I doing wrong?
are you adding the listener before or after the object is created on the DOM?
because if you are trying to bind that onclick function without waiting the document to be ready theres no object to create the listener.
something like this could work:
$(document).on('ready', function() {
$("#MyID").click(function () {
$("#openThis").slideToggle("slow");
});
});
If you button is added dynamically then use on instead of click
Attach an event handler function for one or more events to the
selected elements.
Event handlers are bound only to the currently selected elements; they
must exist at the time your code makes the call to .on()
//Instead of document you can use a container id
$(document).on('click',"#MyID",function () {
$("#openThis").slideToggle("slow");
});
What this approach does is it adds event to a currently selected element which is document here and it will delegate the event to your selector which is #MyID in this case.
Delegated events have the advantage that they can process events from
descendant elements that are added to the document at a later time.
$(document).on('click', '#myBtn', function(){
$('#foo').slideToggle('slow');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div id="foo">content</div>
<button id="myBtn">Click me</button>
You want to scroll to the area so remove the JavaScript from the button
You need to do something like this
$("#MyID").click(function() {
$('html, body').animate({
scrollTop: $("#openThis").offset().top
}, 2000);
$("#openThis").slideToggle("slow");
});
You should delete the onclick="" attributes in the button tag and in your javascript :
$("#MyID").click(function (e) {
e.preventDefault();
$("#openThis").slideToggle("slow");
});
Use the prevent default.
Hope that help

How to activate <a> event by clicking on another element

<div class="imgtumb"><img src="..."></div>
sometext
<script>
$(document).ready(function() {
$('div.imgtumb img').click(function() {
$('a.imgtarget').click();
});
});
</script>
The link not work (dont open a big image). What i do wrong?
----Edited----
Thank you guys, but .trigger() is not working too. I resolved this problem something like this:
$(document).ready(function() {
$('div.imgtumb img').click(function() {
window.location.href = $('a.imgtarget').attr("href");
});
});
----Edited 2---
Question which explained why .click() is not working with a tag
try this:
<script>
$(document).ready(function() {
$('div.imgtumb img').click(function() {
$('a.imgtarget').trigger('click');
});
});
</script>
the event trigger is the event to make another event to an element
http://api.jquery.com/trigger/
use trigger()
. A call to .trigger() executes the handlers in the same order they would be if the event were triggered naturally by the user:
try this
$('a.imgtarget').trigger('click');
instead of
$('a.imgtarget').click();
try to use this instead of .click()
window.open(
'toBigImg',
'_blank'
);

Image not clickable after loaded via AJAX

I have a set of images that are loaded via jQuery AJAX. For some reason, my click handler won't trigger when it is clicked.
JavaScript:
$(document).ready(function()
{
$('img.delete_related_sub').click(function()
{
alert('testing');
});
//I added this part to test, because the above wasn't working...
$(document).click(function(event)
{
alert(event.target.tagName+' '+event.target.className);
});
});
HTML:
<img data-rsid="2" class="delete_related_sub" src="image.png" />
So my 2nd click handler alerts me with "IMG delete_related_sub". But the first one isn't triggered. The is actually in a table that is actually in a pane run by bootstrap tabs, not sure if that'd actually help though.
Try it like this
$(document).on('click', 'img.delete_related_sub', function() {
alert('testing');
});
Just replace document with a static parent of your image.
Use this:
$("body").on('click', 'img.delete_related_sub', function() {
alert('testing');
});
Or, in the success: give this:
$('img.delete_related_sub').click(function() {
alert('testing');
});
Because the line to bind the event runs before the element is added, try using
$(parent).on('click', 'img.delete_related_sub', function() {});
where the parent is a static element that will be there for sure. This works because the event is bound to an element that actually exists, then checks to match your selector. See .on() for more details.
Something like
$(document).on('click', 'img.delete_related_sub', function() {});
would work fine.
$('.delete_related_sub').live("click", function()
{
alert('testing');
});
Use live event to listen clicks

Access dynamically created items using jQuery?

I have a page where some html is being dynamically added to the page.
This is the html and javascript that is created:
<div>
<script type="text/javascript" language="javascript">
$('#btn').click(function() {
alert("Hello");
});
</script>
<a id="btn">Button</a>
</div>
Looking in my Firebug console, I get an error that says:
TypeError: $("#btn") is null
jQuery is being loaded on the page initially.
What am I doing wrong here?
You have to bind on() (or the events defined within the on() method, to an element that exists in the DOM at the point at which the jQuery was run. Usually this is on $(document).ready() or similar.
Bind to the closest element in which the $('#btn') element will be appended that exists in the DOM on page-load/DOM ready.
Assuming that you're loading the $('#btn') into the #container div (for example), to give:
<div id="container">
<div>
Button text
</div>
</div>
Then use:
$('#container').on('click', '#btn', function(){
alert('Button clicked!');
});
Use .on to wire up the event to your button. Check this SO answer:
Event binding on dynamically created elements?
$(document).ready(function() {
$('body').on('click', '#btn', function() {
alert("Hello");
});
})
Edit: I added the document ready code, you'll want to make sure you do that.
Fixed.
you are looking for .on here which will bind the click event to dynamically added nodes.
$("#parent_container").on("click", "#btn", function () {
alert("hello")
})
the docs: http://api.jquery.com/on/
Try
<div>
<a id="btn">Button</a>
</div>
<script>
$('#btn').on('click', function() {
alert("Hello");
});
</script>
The problem in your code is that you are attaching the event to the button before the button is being created.
Correct version is:
<div>
<a id="btn">Button</a>
<script type="text/javascript" language="javascript">
$('#btn').click(function() {
alert("Hello");
});
</script>
</div>
This should do the job.
Use the .live() function of jQuery

jQuery function not binding to newly added dom elements

Here's index.html:
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.btn_test').click(function() { alert('test'); });
});
function add(){
$('body').append('<a href=\'javascript:;\' class=\'btn_test\'>test</a>');
}
</script>
</head>
<body>
test1
add
</body>
If I click on test1 link, it shows alert('test'), but if I click on add link then click on test, it doesn't show anything.
Could you explain it?
For users coming to this question after 2011, there is a new proper way to do this:
$(document).on('click', '.btn_test', function() { alert('test'); });
This is as of jQuery 1.7.
For more information, see Direct and delegated events
You need to use a "live" click listener because initially only the single element will exist.
$('.btn_test').live("click", function() {
alert('test');
});
Update: Since live is deprecated, you should use "on()":
$(".btn_test").on("click", function(){
alert("test");
});
http://api.jquery.com/on/
I have same problem like question I was just near to pulling my hair then i got the solution.
I was using different syntax
$(".innerImage").on("click", function(){
alert("test");
});
it was not working for me (innerImage is dynamically created dom)
Now I'm using
$(document).on('click', '.innerImage', function() { alert('test'); });
http://jsfiddle.net/SDJEp/2/
thanks #Moshe Katz
.click binds to what is presently visible to jQuery. You need to use .live:
$('.btn_test').live('click', function() { alert('test'); });
Use Jquery live instead. Here is the help page for it http://api.jquery.com/live/
$('.btn_test').live(function() { alert('test'); });
Edit: live() is deprecated and you should use on() instead.
$(".btn_test").on("click", function(){
alert("test");
});
This is because you click event is only bound to the existing element at the time of binding. You need to use live or delegate which will bind the event to existing and future elements on the page.
$('.btn_test').live("click", function() { alert('test'); });
Jquery Live
you need live listener instead of click:
$('.btn_test').live('click', function() {
alert('test');
});
The reason being is that the click only assigns the listener to elements when the page is loading. Any new elements added will not have this listener on them. Live adds the click listener to element when the page loads and when they are added afterwards
When the document loads you add event listeners to each matching class to listen for the click event on those elements. The same listener is not automatically added to elements that you add to the Dom later.
Because the event is tied to each matching element in the document ready. Any new elements added do NOT automatically have the same events tied to them.
You will have to manually bind the event to any new element, after it is added, or use the live listener.
$('.btn_test').click
will add the handler for elements which are available on the page (at this point 'test' does not exist!)
you have to either manually add a click handler for this element when you do append, or use a live event handler which will work for every element even if you create it later..
$('.btn_test').live(function() { alert('test'); });
After jquery 1.7 on method can be used and it really works nice
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("p").on("click",function(){
alert("The paragraph was clicked.");
$("body").append("<p id='new'>Now click on this paragraph</p>");
});
$(document).on("click","#new",function(){
alert("On really works.");
});
});
</script>
</head>
<body>
<p>Click this paragraph.</p>
</body>
</html>
see it in action
http://jsfiddle.net/rahulchaturvedie/CzR6n/
Or just run the script at the end of your page
You need to add a proper button click function to give a proper result
$("#btn1").live(function() { alert("test"); });

Categories

Resources