How to show all div's inside images titles onmouseover? - javascript

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/

Related

If else statements to check and see if a certain img tag is appended to div wont execute

I need to check if a div called 'ContainterTwo' has either an image with the class 'hd' or 'tl' appended to it, but my if else block never get executed. The images are html img tags inside an array called 'image'. I use a random generator to stimulate a coin flip.
$(document).ready(function(){
var image = ['<img src="heads.jpg" class="hd" height="50" width="50">', '<img src="tails.jpg" class="tl" height="50" width="50">'];
$('#flip').on('click', function(){
var heads = 0;
var tails = 0;
var numToFlip = parseInt($('#number').val().trim());
for(var x = 0; x < numToFlip; x++)
{
var ran = Math.round(Math.random() * (1)) + 0;
$('.ContainerTwo').append(image[ran]);
if($('.ContainerTwo').hasClass('hd'))
{
heads++;
$('.spOne').html(heads);
$('.ContainerTwo').empty();
}
else if($('.ContainerTwo').hasClass('tl'))
{
tails++;
$('spTwo').html(tails);
$('.ContainerTwo').empty();
}
}
})
})
try this,
if($('.ContainerTwo').find('img').hasClass('hd'))
{
heads++;
$('.spOne').html(heads);
$('.ContainerTwo').empty();
}
else if($('.ContainerTwo').find('img').hasClass('tl'))
{
tails++;
$('spTwo').html(tails);
$('.ContainerTwo').empty();
}
You can check the random value of variable ran.
I have added some code refactor and removed unnecessary variables and moved jQuery variable declarations out of the loop to improve performance.
Code:
$(document).ready(function () {
$('#flip').on('click', function () {
var heads = 0,
tails = 0,
numToFlip = parseInt($('#number').val().trim()),
$spOne = $('.spOne'),
$spTwo = $('spTwo');
for (var x = 0; x < numToFlip; x++) {
var ran = Math.round(Math.random() * (1)) + 0;
(ran === 0) ? $spOne.html(++heads): $spTwo.html(++tails);
}
});
});
Notice that have been removed the image variable because you are doing: $('.ContainerTwo').append(image[ran]); and after that you are doing $('.ContainerTwo').empty();
You can check if multiple class exists with the is() function. You can check all your .ContainerTwo class with each() and compare with your own variable. Try below
var containerTwo = $('.ContainerTwo img'); //All img in your element
containerTwo.each(function(i,e){ //Check all img in all containerTwo element in page
if($(this).is('.hd, .tl')){ // If .hd or tl found
console.log($(this).attr("class"))
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ContainerTwo">
<img class="hd" src="http://img.freepik.com/icones-gratuites/instagram-logo_318-84939.jpg?size=338c&ext=jpg"/>
<img class="tl" src="http://img.freepik.com/icones-gratuites/facebook-logo-bouton_318-84980.jpg?size=338c&ext=jpg"/>
<div>
<div class="ContainerTwo">
<img class="hd" src="http://img.freepik.com/icones-gratuites/instagram-logo_318-84939.jpg?size=338c&ext=jpg"/>
<img class="tl" src="http://img.freepik.com/icones-gratuites/facebook-logo-bouton_318-84980.jpg?size=338c&ext=jpg"/>
<div>

jQuery $(document).on( eventName, selector, function(){} ) not working [duplicate]

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() {

Appended items should stay on hover and be away on leave

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'));

JS Image Transition Not Working

I am unable to get the CSS opacity transition to work by adding it using JavaScript. Please let me know what is wrong with the code. http://jsfiddle.net/copperspeed/bvWbB
(function () {
var myImgs = document.getElementById('vz0');
var i = 0;
function cycle() {
if (i <= 3) {
var myArray = [
'http://jsrun.it/assets/t/r/U/O/trUOT.jpg',
'http://jsrun.it/assets/6/c/Y/s/6cYsH.jpg',
'http://jsrun.it/assets/w/M/r/i/wMriQ.jpg',
'http://jsrun.it/assets/5/Q/8/f/5Q8fW.jpg'
];
console.log(myArray[0]);
myImgs.setAttribute("src", myArray[i]);
if (myImgs.style.opacity === '0') {
console.log('trans');
myImgs.style.transitionProperty = 'opacity';
myImgs.style.transitionDuration = "1500ms";
}
if (myImgs.style.opacity === '1') {
console.log('opacity-0');
myImgs.style.opacity = '0';
}
i++;
setTimeout(function () {
cycle();
}, 3000);
There are a couple of issues with your script.
the opacity style doesn't exist on the element on initialization. You need to account for that in your logic
On the second pass through, the opacity style does exist and may be 0, so that condition also needs to be accounted for
Your second if statement immediately reverses what you did in the first conditional. That statement should be in an else-if
You are cycling only one image element in/out so your transition from one image to another won't work as expected. You either need to change to two elements or change your transitioning strategy to accommodate the single element.
Demo fiddle - items 1-3 above
Code changed for 1-3 above:
(function () {
var myImgs = document.getElementById('vz0');
var i = 0;
function cycle() {
if (i <= 3) {
var myArray = ['http://jsrun.it/assets/t/r/U/O/trUOT.jpg', 'http://jsrun.it/assets/6/c/Y/s/6cYsH.jpg', 'http://jsrun.it/assets/w/M/r/i/wMriQ.jpg', 'http://jsrun.it/assets/5/Q/8/f/5Q8fW.jpg'];
myImgs.setAttribute("src", myArray[i]);
if (myImgs.style.opacity === '' || myImgs.style.opacity == 0) {
console.log(myImgs.style.opacity + '0');
myImgs.style.transitionProperty = 'opacity';
myImgs.style.transitionDuration = "1500ms";
myImgs.style.opacity = 1;
} else if (myImgs.style.opacity == 1) {
console.log(myImgs.style.opacity + '2');
myImgs.style.opacity = 0;
}
i++;
setTimeout(function () {
cycle();
}, 3000);
if (i === 4) {
i = 0;
}
}
}
cycle();
}());
For item #4 above - here is a refactored version that uses two img elements to help manage the transition in and out:
Demo fiddle for 1-4 above
HTML:
<div class="imgWrapper">
<img src="http://jsrun.it/assets/t/r/U/O/trUOT.jpg" id="vz0" class="vzImage" alt="first" height="300" width="300" />
<img src="http://jsrun.it/assets/t/r/U/O/trUOT.jpg" id="vz1" class="vzImage" alt="first" height="300" width="300" />
</div>
CSS:
.imgWrapper {
position: relative;
height: 300px;
width: 300px;
}
.vzImage {
opacity:0;
position: absolute;
top: 0; left: 0;
bottom: 0; right: 0;
}
Script:
(function () {
var myImgs = document.getElementsByClassName('vzImage');
var myArray = ['http://jsrun.it/assets/t/r/U/O/trUOT.jpg',
'http://jsrun.it/assets/6/c/Y/s/6cYsH.jpg',
'http://jsrun.it/assets/w/M/r/i/wMriQ.jpg',
'http://jsrun.it/assets/5/Q/8/f/5Q8fW.jpg'];
// Consider moving this to .vsImage in stylesheet
for(var j = 0; j < myImgs.length; ++j) {
myImgs[j].style.transitionProperty = 'opacity';
myImgs[j].style.transitionDuration = "1500ms";
}
function cycle(i) {
var myArrayIdx = i % myArray.length;
var imgIdx = i % myImgs.length;
var prevImgIdx = (i-1) % myImgs.length;
myImgs[imgIdx].setAttribute("src", myArray[myArrayIdx]);
myImgs[imgIdx].style.opacity = 1;
if(myImgs[prevImgIdx]) {
myImgs[prevImgIdx].style.opacity = 0;
}
setTimeout(function () {
cycle(i+1);
}, 3000);
}
cycle(0);
}());
First rule of debugging. If something inside IF statement doesn't happen, look at the condition.
You check if myImgs.style.opacity equals 0 or 1. Use console.log(myImgs.style.opacity); and it'll show you that myImgs.style.opacity equals empty string. So none of your conditions ever fire.

Adding a new value into img tag to check if it was clicked with Javascript?

I'm trying to make a map with repeated images, and I also want tiles on map to be clickable. Here I wrote a script but I have problem about unchecking checked images.
http://jsbin.com/aruge/edit
Please help.
here's the jQuery version of your requirement Demo : http://jsbin.com/utepi3
$(function() {
var counter = 0;
for(var i = 0;i< 5; i++) {
for(var k = 0; k < 5; k++) {
var img = $('<img />', {
id : 'i'+i+'k'+k,
src: 'http://mclightning.com/gr.jpg',
width : 30,
height : 30,
alt : 'test',
value : '0'
}).appendTo('body').wrap('<div class="hello"/>');
$('.hello').eq(counter).css({
position : 'absolute',
left: i*30,
top : k*30,
cursor : 'pointer'
});
counter++;
}
}
$('img').hover(function() {
if($(this).attr('value') != 1) {
$(this).attr('src', 'http://mclightning.com/grover.jpg');
}
},function() {
if($(this).attr('value') != 1) {
$(this).attr('src', 'http://mclightning.com/gr.jpg');
}
}).bind('click',function() {
if($(this).attr('value') !='1' ) {
$(this).attr('src', 'http://mclightning.com/grclick.jpg');
$(this).attr('value','1');
}else if($(this).attr('value') !='0' ) {
$(this).attr('src', 'http://mclightning.com/gr.jpg');
$(this).attr('value','0');
}
});
});
PS : added image toggler on re-click =)
i don't know exactly what do you want but will that help
function gotover(val) {
if(document.getElementById(val).st!='1') {
x=val.substr(1,1)*30;
y=val.substr(3,1)*30;
document.getElementById(val).src="http://mclightning.com/grover.jpg";
}
}
function gotout(val) {
if(document.getElementById(val).st!='1') {
x=val.substr(1,1)*30;
y=val.substr(3,1)*30;
document.getElementById(val).src="http://mclightning.com/gr.jpg";
}
}
function gotclicked(val) {
alert(document.getElementById(val).alt);
}
var x=0;
var y=0;
for(i=0; i<5; i++)
{
x=i*30;
for(k=0; k<5; k++)
{
y=k*30;
document.write('<div class="kutu" style="position: absolute; left: '+x+'px; top: '+y+'px;"><img onmouseover="gotover(this.id)" onclick="gotclicked(this.id)" onmouseout="gotout(this.id)" id="i'+i+'k'+k+'" src="http://mclightning.com/gr.jpg" width="30" height="30" alt="test"></div>');
}
}

Categories