Associate jquery callback when html change [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Automatically add an event handler to a newly created element using jQuery
I need to associate a jquery callback on a dynamic content.
For example:
<script type="text/javascript">
jQuery(document).ready(function() {
$("#createContent").click(function(){
$("#myCont").append('<img class="myImg" src="icon.png" />');
});
});
</script>
<span id="createContent">click me</span>
<div id="myCont"></div>
If I click over "Click me", it add a image..well, now I want associate a JQuery callback at all the created images, but if I add this code in the .ready(), it doesn't work.
$(".myImg").click(function(){
alert("click on img");
$(this).remove();
} );
There is a way to associate a JQuery callback on runtime?
Here, there is the example in jsFiddle: http://jsfiddle.net/fM8Z7/

Try this:
$("#createContent").click(function () {
var img = document.createElement('img');
img.setAttribute('class', 'myImg');
img.setAttribute('title', 'blabla');
img.setAttribute('src', 'http://icons.iconarchive.com/icons/mid-nights/santa/128/christmas-coupons-icon.png');
img.addEventListener('click', function () {
alert("click on img");
$(this).hide();
});
$("#myCont").append(img);
});
This will create 1 img element, set it's properties, add an event listener, then append the image to #myCont.
Or pure jQuery:
$("#createContent").click(function () {
var img = $('<img class="myImg" title="blabla" src="http://icons.iconarchive.com/icons/mid-nights/santa/128/christmas-coupons-icon.png" />')
.click(function () {
alert("click on img");
$(this).hide();
}
);
$("#myCont").append(img);
});

Try this:
jQuery(document).ready(function() {
var i = 0;
$("#createContent").click(function(){
$("#myCont").append('<img class="myImg" title="blabla" src="http://icons.iconarchive.com/icons/mid-nights/santa/128/christmas-coupons-icon.png" />');
$(".myImg").eq(i).click(function() {
$(this).fadeOut('slow');
});
i++;
});
});​
Demo

try this...
this append the element and initailize click to the appended element only
jQuery(document).ready(function() {
$("#createContent").click(function(){
var appendedItem= $('<img class="myImg" title="blabla" src="http://icons.iconarchive.com/icons/mid-nights/santa/128/christmas-coupons-icon.png" />');
appendedItem.appendTo("#myCont")
.click(function(){
alert("click on img");
$(this).hide();
}
);
});
}) ;​
fiddle here

This should do the magic:
jQuery(document).ready(function() {
var i = 0;
$("#createContent").click(function(){
$("#myCont").append('<img class="myImg" title="blabla" src="http://icons.iconarchive.com/icons/mid-nights/santa/128/christmas-coupons-icon.png" />');
$(".myImg").eq(i).click(function() {
$(this).fadeOut('slow');
});
i++;
});
});​
DEMO

Try this
jQuery(document).ready(function() {
$("#createContent").click(function(){
$("#myCont").append('<img class="myImg" title="blabla" src="http://icons.iconarchive.com/icons/mid-nights/santa/128/christmas-coupons-icon.png" />');
} );
$("#myCont").on('click', function(event){
alert("click on img");
$(event.target).hide();
});
});​
Since the class ".myImg" doesn't exist when you bind the event, you have to bind the click event to an existing element. You can get the image which is clicked using the "event" object.
You can filter image tags using tagName attribute of event.target
Explore jquery event object for further data.
This method helps in avoiding multiple bindings.

Related

Preload image on event

How can I preload image only when event starts, i.e. .scroll or .click ?
What happens now is, image loads along with website, and I want to prevent this from happening.
Thanks.
Use .one() , .appendTo()
$(element).one("click", function() {
$("<img src=/path/to/img/>").appendTo(/* target element */)
})
$(window).one("scroll", function() {
$("<img src=/path/to/img/>").appendTo(/* target element */)
})
Maybe something like this:
$(function() {
$('img').each(function() {
var self = $(this);
self.attr('data-src', self.attr('src'));
self.removeAttr('src');
});
var loaded = false;
function loadImages() {
if (!loaded) {
$('img').each(function() {
var self = $(this);
self.attr('src', self.data('src'));
});
loaded = true;
}
}
$('button').click(loadImages);
$(window).scroll(function() {
loadImages();
$(this).unbind('scroll');
});
});
if the javascript is executed after images are loaded you can try to change img src to data-src in html file.
You could create an image tag with the source in an data attribute:
<img data-src="your_image.jpg">
And then load it on an event:
$('body').on('click', function(){
$('img[data-src]').each(function(i, img){
$img = $(img);
$img.attr('src', $img.data('src'));
$img.removeAttr('data-src');
});
});
This should work
$(function(){
$(document).one("scroll, click", function(){
loadImages();
})
})
Here loadImage is a function which will load your images on click/scroll event. "one" method will make sure that it only happens only once else you will end up loading images every time someone click or scroll.
var src = 'location/file.jpg';
$(document).on('click', function(){
$('target').append('<img src="' +src+ '" />');
});

jquery swap image on element click not functioning

I am trying to swap an image on click with jquery. I have got it to work with the click being bound to the image class. However, if I try and wrap the function and bind the event to a button or anchor, it will not swap the images. Here is the jquery:
<script type="text/javascript">
jQuery(document).ready(function( $ ) {
$(".test_toggle").click(function(){
$(this).find(".img-swap").live('click', function() {
if ($(this).attr("class") == "img-swap") {
this.src = this.src.replace("_off","_on");
} else {
this.src = this.src.replace("_on","_off");
}
$(this).toggleClass("on");
});
});
});
</script>
This worked:
jQuery(document).ready(function( $ ) {
$(".img-swap").live('click', function() {
if ($(this).attr("class") == "img-swap") {
this.src = this.src.replace("_off","_on");
} else {
this.src = this.src.replace("_on","_off");
}
$(this).toggleClass("on");
});
});
Any help is greatly appreciated.
I don't think there's any need to delegate the event listeners so I've removed them. Simply add the click event to the image and then you can manually 'trigger' a click on it when the .test-toggle is clicked. E.G:
$(function() {
//add on click event
$(".img-swap").on('click', function() {
if (this.src.indexOf("_off")>0) {
this.src = this.src.replace("_off","_on");
} else {
this.src = this.src.replace("_on","_off");
}
});
//add remote trigger
$(".test_toggle").on('click', function(){
$(".img-swap").trigger("click");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="img-swap" src="https://placehold.it/300?text=_off" />
<button class="test_toggle">test toggle</button>
Thats because unlike like img.
a or button doesn't have a src attribute.
So when you bind the event to a button or anchor, this.src in your second instance of the code will be invalid.
I would delete this line:
$(this).find(".img-swap").live('click', function() {
What is it's purpose? You can swap this image right after the first click, right?
Also, make sure that .img-swap is inside the tag with class test_toggle.
You are using:
$(this).find(".img-swap")
find() searches only in children of selected element.
If it's not nested use
$(".img-swap")
instead of:
$(this).find(".img-swap")
I have re-written the js, but not tested. Can I nest clicks?
$(".test_toggle").click(function(){
$.find(".img-swap").click(function(){
if ($(this).attr("class") == "img-swap") {
this.src = this.src.replace("_off","_on");
} else {
this.src = this.src.replace("_on","_off");
}
$(this).toggleClass("on");
});
});

unable to set CSS and click handler in jQuery after use of replaceWith() [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 8 years ago.
I am using jQuery to replace normal checkbox with image. I am able to replace checkbox with image but unable to set CSS and click handler on image.
This is my jQuery code.
(function ($) {
$.fn.SetOnOff = function (onImage,offImage) {
debugger;
var html = '<img style="width: 80px; height: 30px" src="'+offImage +'"/>';
$(this).replaceWith(html);
$(html).css('cursor','pointer');
$(html).click(function(){
var fileName = $(this).attr('src');
if (fileName == onImage)
$(this).attr('src', offImage);
else
$(this).attr('src', onImage);
});
return $(this);
};
} (jQuery));
can anybody let me know how to do this?
you use This link to test it
use event delegation for dynamically created element
$("button").click(function () {
var v = "<div>" + $(this).text() + "</div>";
$(this).replaceWith(v);
$(v).css('cursor', 'pointer');
});
$(document).on("click", "div", function () {
alert($(this).text());
});
DEMO
Your css and click methods are not being called on the replaced element but on a newly-created HTML jQuery is generating from your html string.
Try this instead:
var $v = $("<div>" + $(this).text() + "</div>");
$(this).replaceWith($v);
$v.css('cursor', 'pointer');
$v.click(function () {
alert('a');
});
you are trying to set css to string. make it jquery object just like below
(function ($) {
$.fn.SetOnOff = function (onImage,offImage) {
debugger;
var html = $('<img style="width: 80px; height: 30px" src="'+offImage +'"/>');
$(this).replaceWith(html);
$(html).css('cursor','pointer');
$(html).click(function(){
var fileName = $(this).attr('src');
if (fileName == onImage)
$(this).attr('src', offImage);
else
$(this).attr('src', onImage);
});
return $(this);
};
} (jQuery));
Demo

Jquery: Replace image source getting link from anchor tag

I need a help and I am stuck how to replace a image source by getting the url link from its anchor tag.
And I need to repeat this for a n number of div.
What I have is n number of div, and a anchor tag in each div with a image.
When someone hover on a image tag, the source of image should changed by getting the source from anchor tag and I also want to disable the anchor click. Is this possible?
Have a look at the code:
<div class="slide" data-type="image">
<a href="http://www.extremetech.com/wp-content/uploads/2012/12/Audi-A1.jpg">
<img data-image="http://earnthis.net/wp-content/uploads/2013/09/Toy-Story-2-Disney-Wallpaper-Picture.jpg"
data-src="http://earnthis.net/wp-content/uploads/2013/09/Toy-Story-2-Disney-Wallpaper-Picture.jpg"
src="http://earnthis.net/wp-content/uploads/2013/09/Toy-Story-2-Disney-Wallpaper-Picture.jpg"
/>
</a>
http://jsfiddle.net/7AqkS/1/
Thanks, I am not good in jquery :(
You can achieve basic rollover effect with this code:
$(".slide a").hover(function() {
$(this).find('img').prop('src', this.href);
}, function() {
$(this).find('img').prop('src', function() {
return $(this).data('src');
});
})
.on('click', function(e) { e.preventDefault(); })
Demo: http://jsfiddle.net/7AqkS/6/
Or if you want something fancier:
$('.slide a').on({
'mouseover mouseout': function(e) {
$('img', this).prop('src', function() {
return e.type == 'mouseover' ? e.delegateTarget.href : $(this).data('src');
});
},
click: function(e) {
e.preventDefault();
}
});
Look for the parents 'href' attribute and set the images 'src' attribute to its value, like this.
$( document ).ready( function() {
// One way che
$( ".slide img" ).hover( function( element ){
var image = $( this );
var newImage = image.parent( 'a' ).attr( 'href' );
image.attr( 'src', newImage );
});
// Prevent Default anchor behavior
$( ".slide a" ).click( function(element){
element.preventDefault();
element.stopPropagation();
});
});
This might help you http://jsfiddle.net/7AqkS/8/
HTML:
<div class="slide" data-type="image"> <a href="http://scm-l3.technorati.com/11/08/30/49859/Google+steel.png?t=20110830212412">
<img data-image="http://www.technewspaper.net/wp-content/uploads/2013/05/google1.jpg"
data-src="http://scm-l3.technorati.com/11/08/30/49859/Google+steel.png?t=20110830212412"
src="http://www.technewspaper.net/wp-content/uploads/2013/05/google1.jpg"/>
</a>
</div>
<div class="slide" data-type="image">
<a href="http://scm-l3.technorati.com/11/08/30/49859/Google+steel.png?t=20110830212412">
<img data-image="http://www.technewspaper.net/wp-content/uploads/2013/05/google1.jpg"
data-src="http://scm-l3.technorati.com/11/08/30/49859/Google+steel.png?t=20110830212412"
src="http://www.technewspaper.net/wp-content/uploads/2013/05/google1.jpg"/>
</a>
</div>
JS:
$(document).ready(function(){
$(".slide img").on("mouseenter", function () {
$(this).attr("src", $(this).data("src"));
}).on("mouseleave", function () {
$(this).attr("src", $(this).data("image"));
});
});

How to display image src before href in jQuery

Have this block:
jQuery(document).ready(function($) {
$("img[src$='.jpeg'], img[src$='.jpg'], img[src$='.png'], img[src$='.gif']").wrap('<div class="b-img"/>').each(function() {
var src = $(this).attr('src');
var a = $('<a/>').attr('href', src).addClass('img-link').colorbox();
$(this).wrap(a);
});
})(jQuery);
and after that have link like <img src>... but I need <img src> before <a href="">
You can use after() instead of wrap
jQuery(document).ready(function($) {
$("img[src$='.jpeg'], img[src$='.jpg'], img[src$='.png'], img[src$='.gif']").wrap('<div class="b-img"/>').each(function() {
var src = $(this).attr('src');
var a = $('<a/>').attr('href', src).addClass('img-link').colorbox();
$(this).after(a);
});
})(jQuery);
Edit based on comments by OP, for changing image src
jQuery(document).ready(function($) {
$("img[src$='.jpeg'], img[src$='.jpg'], img[src$='.png'], img[src$='.gif']").wrap('<div class="b-img"/>').each(function() {
var src = $(this).attr('src');
var a = $('<a/>').attr('href', src).addClass('img-link').colorbox();
$(this).after(a);
$(this).attr('src', 'http://www.yoursite.com/images/img1.jpg');
});
})(jQuery);
insertBefore() inserts the elements before this, like so:
$(function() {
$("img").wrap('<div class="b-img"/>').each(function() {
$('<a />', {href: this.src, 'class': 'img-link'}).colorbox().insertBefore(this);
});​
});​
Also, there should be no need to check for all available image file extensions, if you have images that are svg etc, use a class instead.

Categories