Javascript function not working for all elements - javascript

I'm trying to write a script which changes image on mouse hover. I have 6 images, but the function is working for only one of them (the first one)
<div id="picture-container">
<img class="picture" id="360" src="360.jpg" onclick="enlarge(360);" onmouseover="pic_info(360);"
onmouseout="pic_ret(360);"/>
<img class="picture" id="bmx" src="bmx.jpg" onclick="enlarge(bmx);"/>
<img class="picture" id="buzludzha" src="buzludzha.jpg" onclick="enlarge(buzludzha);"
onmouseover="pic_info(buzludzha);"/>
<img class="picture" id="pirata" src="pirata.jpg" onclick="enlarge(pirata);"
onmouseover="pic_info(pirata);"/>
<img class="picture" id="snowboard" src="snowboard.jpg" onclick="enlarge(snowboard);"
onmouseover="pic_info(snowboard);"/>
<img class="picture" id="vitiskali" src="vitiskali.jpg" onclick="enlarge(vitiskali);"
onmouseover="pic_info(vitiskali);"/>
<img class="picture" id="ispolin" src="ispolin.jpg" onclick="enlarge(ispolin);"
onmouseover="pic_info(ispolin);"/>
</div>
And the script:
function pic_info(id) {
if (id == "360") {
var p = document.getElementById(id);
p.src = "360info.jpg";
}
if (id == "buzludzha") {
var p = document.getElementById(id);
p.src = "buzludzhainfo.jpg";
}
if (id == "pirata") {
var p = document.getElementById(id);
p.src = "piratainfo.jpg";
}
if (id == "snowboard") {
var p = document.getElementById(id);
p.src = "snowboardinfo.jpg";
}
if (id == "vitiskali") {
var p = document.getElementById(id);
p.src = "vitiskaliinfo.jpg";
}
if (id == "ispolin") {
var p = document.getElementById(id);
p.src = "ispolininfo.jpg";
}
As I said the script works only for picture with id="360" and it is imported in the head tag of the html document.The same thing happens with the function "enlarge();". Why is that and how can I fix it?
Thank you, in advance!

just to scratch the surface, are passing a variable instead of a string : enlarge(bmx); should be : enlarge('bmx');, and so on for the others

Related

How to get a list of the elements in a given div using JavaScript

In a given id of a <div> I need to get a list of all the elements which are in that div.
My goal is to get a list of all elements in the given div and loop over them hide everyone except the first one.
Example:
<div id="RandomId">
<img src="src_1" />
<img src="src_2" />
<img src="src_3" />
.
.
.
<img src="src_n" />
</div>
<script>
function handleImages(divID) {
const div = document.getElementById(DivID);
if(div) {
const Elements = // Here, I need the list;
for (let i = 0; i < Elements.length; i++) {
if (i == 0) {
continue;
}
else {
Elements[i].style = "display:block";
}
}
}
return null;
}
</script>
You could also use querySelectorAll:
const Elements = document.querySelectorAll('#RandomId > img')
You need to use Element.children to get the list of elements inside the div.
That's very easy to do when you're using native JavaScript. Use the following:
<script>
function handleImages(divID){
const div = document.getElementById(DivID);
if(div){
const Elements = div.children //Here, I need the list;
for (let i = 0; i < Elements.length; i++){
if (i == 0) { continue; }
else {Elements[i].style = "display:block";}
}
}
return null;
}
</script>
More details about Element.children.
You can use querySelectorAll to get rid of first child as:
function handleImages(id) {
const allChildren = [...document.querySelectorAll(`#${id} > img`)];
allChildren.forEach(
(imgChild, index) =>
(imgChild.style.display = index === 0 ? "block" : "none")
);
}
handleImages("RandomId");
<div id="RandomId">
<img src="https://picsum.photos/200/300" />
<img src="https://picsum.photos/200/300" />
<img src="https://picsum.photos/200/300" />
<img src="https://picsum.photos/200/300" />
</div>

onclick: picture does not change

My goal is to randomly change an image by clicking on a button. I have found a snippet that does that but I wanted to train my skills and work my way through it, this is what I got so far:
When I click the button, with the variable on line 11, nothing happens, but when I put the URL instead of the variable (copied from the console from line 22), it goes to the according picture. I don't get it...
When my "imageCount" is full, I get an error
var imageCount = [];
var image = ["img/01.jpg", "img/02.jpg", "img/03.jpeg", "img/04.jpeg"];
function changeImage() {
var rand = Math.floor(Math.random() * image.length);
var imageNumber = "\"url('" + image[rand] + "')\""
if (imageCount.indexOf(rand) === -1) {
imageCount.push(rand);
document.getElementById("imageWrapper").style.backgroundImage = imageNumber;
} else if (imageCount.length === image.length) {
imageCount = 0;
} else {
changeImage();
}
console.log(imageNumber);
console.log(imageCount.indexOf(rand));
console.log(image[rand]);
console.log(imageCount);
}
<link href="./style/main.css" rel="stylesheet">
<div class="wrapper">
<div class="buttonWrapper">
<button class="button" onclick="changeImage()">Next Pic</button>
</div>
<div id="imageWrapper">
<!--<img src="./img/02.jpg" alt="" id="random">-->
</div>
</div>
Two things stop your demo code from working:
#imageWrapper has no height, so the image is not displayed (probably only because your page's CSS is missing)
You reset the imageCount variable to 0 instead of []
var imageCount = [];
var image = ["//baconmockup.com/300/199/", "//baconmockup.com/300/200/", "//baconmockup.com/300/201/", "//baconmockup.com/300/202/"];
function changeImage() {
var rand = Math.floor(Math.random() * image.length);
var imageNumber = "url('" + image[rand] + "')"
if (imageCount.indexOf(rand) === -1) {
imageCount.push(rand);
document.getElementById("imageWrapper").style.backgroundImage = imageNumber;
}
else if (imageCount.length === image.length) {
imageCount = [];
}
else {
changeImage();
}
console.log(imageNumber);
console.log(imageCount.indexOf(rand));
console.log(image[rand]);
console.log(imageCount);
}
#imageWrapper {
height: 200px;
outline: solid black 1px;
}
<div class="wrapper">
<div class="buttonWrapper">
<button class="button" onclick="changeImage()">Next Pic</button>
</div>
<div id="imageWrapper">
<!--<img src="./img/02.jpg" alt="" id="random">-->
</div>
</div>

getelementbyid in firefox onclick display:block script troubleshooting

I have a script which toggles block/none display of a div, onClick. The onClick also toggles an associated "thumbnail" image from active to inactive.
Only in Firefox, the div's stack on top of each other. It seems as if the onClick is not associating the display:none style with the current item.
I made sure that all divs have associated ID's which seems to be the top questions related to getElementById issues in Firefox.
Any thoughts on troubleshooting this would be helpful, thank you!
Here is my javascript:
var curVid = "VideoA";
var curImg = "VideoA_thumbnail";
function changeVideo(id, img)
{
if(document.getElementById(id) != null && curVid != id)
{
document.getElementById(curVid).style.display = "none";
document.getElementById(id).style.display = "block";
document.getElementById(id + "_thumb").src = "..//Thumbnails//" + img + "_selected.jpg";
document.getElementById(id + "_thumb").style.cursor = "default";
document.getElementById(curVid + "_thumb").src = "..//Thumbnails//" + curImg + ".jpg";
document.getElementById(curVid + "_thumb").style.cursor = "pointer";
if(VideoJS.browserSupportsVideo())
{
document.getElementById(curVid + "_video").pause();
document.getElementById(curVid + "_video").currentTime = 0;
VideoJS.setup(id + "_video");
document.getElementById(id + "_video").play();
}
else
{
$f(curVid + "_flash").stop();
$f(id + "_flash").play();
}
curVid = id;
curImg = img;
}
}
and this is the HTML
<div id = "VideoA" style = "display:block;">content here</div>
<div id = "VideoB" style = "display:none;">content here</div>
<div id = "VideoC" style = "display:none;">content here</div>
<div id = "VideoD" style = "display:none;">content here</div>
<div id = "VideoE" style = "display:none;">content here</div>
<div>
<img src = "a.jpg" id = "VideoA_thumb" onclick = "changeVideo('VideoA', 'VideoA_thumb')" />
<img src = "b.jpg" id = "VideoB_thumb" onclick = "changeVideo('VideoB', 'VideoB_thumb')" />
<img src = "c.jpg" id = "VideoC_thumb" onclick = "changeVideo('VideoC', 'VideoC_thumb')" />
<img src = "d.jpg" id = "VideoD_thumb" onclick = "changeVideo('VideoD', 'VideoD_thumb')" />
<img src = "e.jpg" id = "VideoE_thumb" onclick = "changeVideo('VideoE', 'VideoE_thumb')" />
</div>

Sorting images by their ID [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to sort LI's based on their ID
I have a div that is dynamically populated with various images and looks something like:
<div id="images">
<img id="img1" src="..." />
<img id="img3" src="..." />
<img id="img2" src="..." />
<img id="img6" src="..." />
<img id="img5" src="..." />
<img id="img4" src="..." />
</div>
Using javascript and jQuery, i need to sort the images into order of ID but i'm struggling. Heres what I've got so far:
var toSort = $('#images').children;
toSort = Array.prototype.slice.call(toSort,0);
toSort.sort(function(a,b){
var aord = +a.id.substr(6);
var bord = +b.id.substr(6);
return aord - bord;
});
var parent = $('#images');
parent.innerHTML="";
for(var i=0, l = toSort.length; i<l; ++i){
parent.appendChild(toSort[i]);
}
How close am I? What am I doing wrong? Thanks guys.
var imgs = $('#images img');
imgs.sort(function(a, b) {
return a.id > b.id;
});
$('#images').html(imgs);
​
DEMO
OR
var imgs = $('#images img');
imgs.sort(function(a, b) {
return +a.id.replace('img','') - +b.id.replace('img','');
});
$('#images').html(imgs);
DEMO
Edition with your code:
var parent = $('#images'),
children = parent.children(),
toSort = Array.prototype.slice.call(children, 0);
parent[0].innerHTML = ""; //or parent.empty();
toSort.sort(function(a, b) {
var aord = +a.id.substr(3);
var bord = +b.id.substr(3);
return aord - bord;
});
for (var i = 0; i < toSort.length; i++) {
parent.append(toSort[i]);
}
DEMO
var elem = $('#images'),
imgs = elem.find('img');
imgs.sort(function(a, b) {
return a.id.toUpperCase().localeCompare(b.id.toUpperCase());
});
$.each(imgs, function(idx, itm) { elem.append(itm); });
FIDDLE
I think #thecodeparadox version is better but here is your code corrected a little bit. I changed img to span to make it more visible.
http://jsfiddle.net/whnyn/

Hiding/Showing Div Elements

This should cycle through the <div> tags, but it isn't even showing the first one. It should show a "0", then 50ms later, show "1", then "2", and then "3". I get nothing.
Here's the HTML:
<div class="header" id="animation">
<div id="aniObj0" style="display: none;" onLoad="runAnimation();">0</div>
<div id="aniObj1" style="display: none;">1</div>
<div id="aniObj2" style="display: none;">2</div>
<div id="aniObj3" style="display: none;">3</div>
</div>
The JavaScript:
var aniNum = 0;
var animationDelay = 50;
var frameDelay = 50;
function runAnimation()
{
Console.log("runningAnimation");
var prevObj = document.getElementById('aniObj' + (aniNum - 1));
var aniObj = document.getElementById('aniObj' + aniNum);
if(aniObj != null){
if(prevObj != null){
aniObj.style.display = 'none;';
}
aniObj.style.display = 'block;';
aniNum++;
if(aniNum == 0){
setTimeout("runAnimation();", animationDelay);
}else{
setTimeout("runAnimation();", frameDelay);
}
}else{
aniNum = 0;
newAnimation();
}
}
You're very close. See code below (and comments in code).
HTML:
<div class="header" id="animation">
<!-- Removed onload="runAnimation()" - onload doesn't exist for a div -->
<div id="aniObj0" style="display: none;">0</div>
<div id="aniObj1" style="display: none;">1</div>
<div id="aniObj2" style="display: none;">2</div>
<div id="aniObj3" style="display: none;">3</div>
</div>
JavaScript:
var aniNum = 0;
var animationDelay = 500; //Changed to 500ms to you could see better
var frameDelay = 500; //Changed to 500ms to you could see better
function runAnimation()
{
var prevObj = document.getElementById('aniObj' + (aniNum - 1));
var aniObj = document.getElementById('aniObj' + aniNum);
if (aniObj != null) {
if (prevObj != null) {
aniObj.style.display = 'none;';
}
aniObj.style.display = '';
aniNum++;
if (aniNum == 0) {
//Changed setTimeout("runAnimation()", animationDelay); to
//setTimeout(runAnimation, animationDelay);
setTimeout(runAnimation, animationDelay);
} else {
setTimeout(runAnimation, frameDelay);
}
} else {
aniNum = 0;
newAnimation();
}
}
//You need to place this in a valid event. onload event of the body maybe?
runAnimation();
Here's a working fiddle.

Categories