This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 6 years ago.
I had a click function which functioned when I had this elements hidden on page load, and then showed them later. Now I am appending those elements on click after the page has loaded, and the function of course doesn't work. I thought I would fixed the problem with load() function but it still doesn't work. This is the html I append on click:
$('#magazine-detail')[0].innerHTML = '<section id="magazine-detail" class="magazine-detail"><div class="large-6 medium-6 small-12 columns"><div class="magazine-hero"><img id="image" src="/imagecache/cover/' + magazineImage + '" alt="' + name + '" /><div class="magazine-preview-nav"><div class="right-arrow" id="forward"><img src="/img/right-arrow-black.svg" /><p>Neste utgivelse</p></div><div class="left-arrow" id="back"><img src="/img/left-arrow-black.svg" /><p>Forrige utgivelse</p></div></div></div></div><div class="large-6 medium-6 small-12 columns"><div class="row"><div class="small-6 columns magazine-title"><h1 id="name"></h1></div></div><p id="summary"></p><img id="issueImage" src="" alt="" /><p></p><button class="button primary expand">Kjøp abonnement - 1 måned gratis</button><button class="button secondary expand">Bla igjennom arkivet</button></div></section>';
There I create #forward and #back elements, for which I have functions on click in my script:
$(document).ready(function () {
var imagesIndex = 0;
nextImage = 0;
loadedImages = new Array();
function preload() {
for (i = 0; i < 2; i++) {
if (nextImage < images.length) {
var img = new Image();
img.src = '/imagecache/cover/' + images[nextImage];
loadedImages[nextImage] = img;
++nextImage;
}
}
}
$('#forward').load('click', function() {
imagesIndex++;
preload();
if (imagesIndex > (loadedImages.length - 1)) {
imagesIndex = loadedImages.length - 1;
}
$('#image').attr({"src" : loadedImages[imagesIndex].src, "alt" : name});
});
$('#back').load('click', function() {
imagesIndex--;
if (imagesIndex < 0) {
imagesIndex = 0;
}
$('#image').attr({"src" : loadedImages[imagesIndex].src, "alt" : name});
});
});
I have tried with:
$(document).on('click','#forward', function() {
console.log('entered');
imagesIndex++;
preload();
if (imagesIndex > (loadedImages.length - 1)) {
imagesIndex = loadedImages.length - 1;
}
$('#image').attr({"src" : loadedImages[imagesIndex].src, "alt" : name});
});
$(document).on('click','#forward', function() {
imagesIndex--;
if (imagesIndex < 0) {
imagesIndex = 0;
}
$('#image').attr({"src" : loadedImages[imagesIndex].src, "alt" : name});
});
But nothing gets logged when I click on the element.
$("#existingParent").on("click", ".child", function() {
// do stuff
});
write like this
$(document).on('click','#forward', function() {
Related
var n=0;
var images=["FullSizeRender (1).jpg","IMG_1875.JPG","IMG_4665.JPG","IMG_5213.JPG"];
$(document).ready(function() {
// Change image
$("#himg").click(function(){
n++;
if(n==images.length){
n=0;
};
document.getElementById("himg").src=images[n];
$("#himg").find('img[src="' + images[n] + '"]').fadeOut();
$("#himg").find('img[src="' + images[n+1] + '"]').hide().fadeIn();
});
<div class="col-xs-2">
<div id="handbags">
<h4>Handbags</h4>
<img id="himg" src="FullSizeRender (1).jpg" />
</div>
</div>
I have made an array where images change on click, but I am trying to make the images fade on click instead of sharply changing. I've tried selecting the images by source using the index from the array, but it's not working.
Try this:
$(document).ready(function() {
var n = 0;
var images = ["FullSizeRender(1).jpg","IMG_1875.JPG","IMG_4665.JPG","IMG_5213.JPG"];
var image = $('#himg');
image.on('click', function() {
var newN = n+1;
if (newN >= images.length) { newN = 0 };
image.attr('src', images[n]);
image.fadeOut(300, function () {
image.attr('src', images[newN]);
image.fadeIn();
n = newN;
});
});
});
I would like to limit click event loop in jquery. I have categories list which will have in the following format and also after 5 click in the loop i have to disable click event.
<div class="col-md-2 col-sm-4 col-xs-6 home_s">
<a class="get_category" id="36" href="javascript:void(0)">
<img class="img-responsive img-center" src="">
<span>xxxxx</span>
</a>
<input type="hidden" value="36" id="categories36" name="categories[]">
</div>
$(document).ready(function() {
$(".get_category").on('click', function() {
var cat_id = $(this).attr('id');
var cat_value = $("#categories" + cat_id).val('');
if ($("#categories" + cat_id).val() == '') {
$("#categories" + cat_id).val(cat_id);
} else {
alert("hi");
$("#categories" + cat_id).val('');
}
})
});
You can use off() to unbind event handler
$(document).ready(function() {
// variable for counting clicks
var i = 1;
var fun = function() {
var cat_id = $(this).attr('id');
var cat_value = $("#categories" + cat_id).val('');
if ($("#categories" + cat_id).val() == '') {
$("#categories" + cat_id).val(cat_id);
} else {
alert("hi");
$("#categories" + cat_id).val('');
}
// checking and increment click count
if (i++ == 5)
// unbinding click handler from element
$(".get_category").off('click', fun);
};
$(".get_category").on('click', fun);
});
Example :
$(document).ready(function() {
var i = 1;
var fun = function() {
alert('clicked'+i);
if (i++ == 5)
$(".get_category").off('click', fun);
};
$(".get_category").on('click', fun);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="get_category">click</button>
If you have multiple .get_category in your html the solution from Pranav C Balan won't work.
$(document).ready(function() {
function clickFunc() {
var click_count = $(this).data('click-count') || 0;
var cat_id = $(this).attr('id');
var cat_value = $("#categories" + cat_id).val('');
if ($("#categories" + cat_id).val() == '') {
$("#categories" + cat_id).val(cat_id);
} else {
alert("hi");
$("#categories" + cat_id).val('');
}
if (++click_count >= 5)
$(this).off('click', clickFunc);
$(this).data('click-count', click_count);
});
$(".get_category").on('click', clickFunc);
});
This way you store the click count on the data-click-count attribute of each .get_category
Basically when someone hovers over one certain item, more items should appear (which works) but when the mouse leaves that item, the items dissapear.
However I want the "hover area" to be the whole div containing the appended items so that the user can go through all the new IMGs
JavaScript
$("#mood").hover(
function() {
for (var i = 0; i < imgArr.length; i++) {
var img = $('<img />');
if (imgArr[i] != "") {
var img = $('<img />', {
src: '../img/mood/' + imgArr[i],
class: 'mood-item',
name: i
});
img.appendTo($('#mood-list'));
}
}
},
function() {
$("#mood-list img:gt(0)").remove()
}
);
HTML
<div class="form-group">
<label class="col-md-3 col-sm-4 control-label">Mood</label>
<div class="col-md-9 col-sm-8" id="mood-list">
<img src="...." id="mood"/>
</div>
</div>
You will have to use two different events since your condition is #mood-list div should be populated when #mood is hovered yet should be emptied when #mood-list no longer has the cursor
$("#mood").hover(
function() {
for (var i = 0; i < imgArr.length; i++) {
var img = $('<img />');
if (imgArr[i] != "") {
var img = $('<img />', {
src: '../img/mood/' + imgArr[i],
class: 'mood-item',
name: i
});
img.appendTo($('#mood-list'));
}
}
}
);
$('#mood-list').mouseleave(
function() {
$("#mood-list img:gt(0)").remove()
});
Update
if I hover 2 times over the first element (which causes the others to
appear), every item appears twice
In your case, you can check for siblings like
$("#mood").hover(
function() {
if(!$(this).siblings().length){
for (var i = 0; i < imgArr.length; i++) {
var img = $('<img />');
if (imgArr[i] != "") {
var img = $('<img />', {
src: '../img/mood/' + imgArr[i],
class: 'mood-item',
name: i
});
img.appendTo($('#mood-list'));
}
}
}
}
);
Do you know what I have to change if I want to put this img into a
?
Replace
img.appendTo($('#mood-list'));
with
var anchor = $('<a></a>');
img.appendTo(anchor);
anchor.appendTo($('#mood-list'));
I have a div containing images and I want to show all of the inside image's titles onmouseover.
So, I have something like this :
<div id=MyDiv onmouseover="highlight(this);">
And my javascript :
function highlight(element) {
for (var i = 0; i < element.children.length; i++) {
if (element.children[i].tagName == "IMG")
element.children[i].title.show();
}
}
But all i get is a message - Object "X" has no method show.
You are using plain JavaScript. title is a string, and as the message says, it has no method show.
If what you want to do is alert all the titles in a pop-up, you can do this:
function highlight(element) {
for (var i = 0; i < element.children.length; i++) {
if (element.children[i].tagName == "IMG")
alert(element.children[i].title);
}
}
If, on the other hand you want to show them on your page you need something like this:
function highlight(element) {
var outputelement = document.getElementById("idofsomeelementyouhaveonyourpage");
for (var i = 0; i < element.children.length; i++) {
if (element.children[i].tagName == "IMG")
outputelement.innerHTML += element.children[i].title;
}
}
Of course, with the second method, you'd need an onmouseout handler that hides the titles as well.
Here is an example using jQuery:
HTML:
<div id="MyDiv">
<img src="http://chandra.harvard.edu/photo/2012/m101/m101_xray_thm100.jpg" title="img1" />
<img src="http://passport-cdn.mobilenations.com/avatars/000/004/072/100x100_4072871.jpg?r=1" title="img2" />
</div>
jQuery:
$("#MyDiv").mouseenter(function () {
$mydiv = $(this);
$.each($('img', $mydiv), function () {
var pos = $(this).position();
$('<div>', {
class: 'imgtitle'
}).css({
position: 'absolute',
color: 'red',
top: pos.top + 5,
left: pos.left + 5
})
.html($(this).attr('title'))
.insertAfter($(this));
});
}).mouseleave(function () {
$('.imgtitle').remove();
});
Here's a jsfiddle showing it in action: http://jsfiddle.net/obryckim/k5hcJ/
This question uses jquery.
In the card game below, one image will be used to make 2 matching cards. Cards are matched based on having the same file source.(ie if 2 cards have the same file source then they are a match).
What I'd like to do is match the cards based on different criteria. This is because I'd like to use 2 different images as the matching pair.
At first I thought that I could just specify values for the matching images, but when the cards are shuffled at the start/reset of each game, the values don't move with the image.
To sum up, I'd like to find a way to match 2 cards(images) that have differing file sources after they have been randomly shuffled.
Any help would be much appreciated. Thanks.
<script type="text/javascript">
var boxopened = "";
var imgopened = "";
var count = 0;
var found = 0;
function randomFromTo(from, to){
return Math.floor(Math.random() * (to - from + 1) + from);
}
function shuffle() {
var children = $("#boxcard").children();
var child = $("#boxcard div:first-child");
var array_img = new Array();
for (i=0; i<children.length; i++) {
array_img[i] = $("#"+child.attr("id")+" img").attr("src");
child = child.next();
}
var child = $("#boxcard div:first-child");
for (z=0; z<children.length; z++) {
randIndex = randomFromTo(0, array_img.length - 1);
// set new image
$("#"+child.attr("id")+" img").attr("src", array_img[randIndex]);
array_img.splice(randIndex, 1);
child = child.next();
}
}
function resetGame() {
shuffle();
$(".tile").hide();
$("img").removeClass("opacity");
count = 0;
$("#msg").remove();
$("#count").html("" + count);
boxopened = "";
imgopened = "";
found = 0;
return false;
}
$(document).ready(function() {
$(".tile").hide();
$("#boxcard div").click(openCard);
shuffle();
function openCard() {
id = $(this).attr("id");
if ($("#"+id+" img").is(":hidden")) {
$("#boxcard div").unbind("click", openCard);
$("#"+id+" img").slideDown('fast');
if (imgopened == "") {
boxopened = id;
imgopened = $("#"+id+" img").attr("src");
//print imgopened
$('#reading1').html('<h1> imgopened is '+imgopened+'</h1>');
setTimeout(function() {
$("#boxcard div").bind("click", openCard)
}, 300);
} else {
currentopened = $("#"+id+" img").attr("src");
//print currentopened
$('#reading2').html('<h1> currentopened is '+currentopened+'</h1>');
if (imgopened != currentopened) {
// close again
setTimeout(function() {
$("#"+id+" img").slideUp('fast');
$("#"+boxopened+" img").slideUp('fast');
boxopened = "";
imgopened = "";
}, 400);
} else {
// found
$("#"+id+" img").addClass("opacity");
$("#"+boxopened+" img").addClass("opacity");
found++;
boxopened = "";
imgopened = "";
}
setTimeout(function() {
$("#boxcard div").bind("click", openCard)
}, 400);
}
count++;
$("#count").html("" + count);
if (found == 10) {
msg = '<span id="msg">Congrats ! You Found All The Cards With </span>';
$("span.link").prepend(msg);
}
}
}
});
</script>
Here is the html
<div id="reading1" style="display:block; width:700px; height:50px;"></div>
<br/>
<div id="reading2" style="color:#cc0000; display:block; width:700px; height:50px;"></div>
<div id="boxbutton">
<span class="link">
<span id="count">0</span>
Click
</span>
Restart
</div>
<div id="boxcard">
<div id="card1"><img class="tile" src="img/01.jpg" /></div>
<div id="card10"><img class="tile" src="img/01.jpg" /></div>
</div>
I would use the .data() method of jQuery to "attach" a specific piece of data that matches the "criteria" you need for the matched images. Then as you "turn over" a "card" you can extract the specific piece of data and compare it to another card that is turned over to see if they match. Because the data is a property of the image, it will "move" with the image when it is shuffled.