Javascript - Resizing Slideshow Images - javascript

I am trying to make a slideshow in JavaScript, and I want to show only half images, but I have a problem. Some images have width and height equal to 0 in Chrome and Opera. Why?
HTML
<img id="picArt" src="0.jpg" onload="resizeImage();" /> <br />
<input type="button" value="Back" onclick="slidePic('P');" />
<input type="button" value="Forward" onclick="slidePic('N');" />
JavaScript
var picArt = document.getElementById("picArt");
var picLocal = new Array();
for(var num=0;num<=17;num++) {
picLocal[num] = String(num) +".jpg";
}
var desrib = new Array();
var preLoad = new Array();
var next = 0, picLength = (picLocal.length-1);
for(var num=0;num <= picLength; num++) {
preLoad[num] = new Image();
preLoad[num].src = picLocal[num];
}
function slidePic (how) {
if(how == "N") next++;
if(how == "P") next--;
if(next> picLength) next =0;
if(next <0) next = picLength;
picArt.src = preLoad[next].src;
}
function resizeImage() {
var originImage = new Image();
originImage.src = picArt.src;
picArt.width = originImage.width/2;
picArt.height = originImage.height/2;
}

May be resize images in CSS, not JavaScript?
Example:
img{
width:200px;
max-width:200px;
}
resized width and height automatically, without js

Related

It doesn't move to the next image

I am trying to create a slideshow. I have created two buttons because I want to do it in two ways. One way is when I press the next button to move to the next image(single image movement) and when I press the slideshow button to make it move along with not pressing a button. I didn't manage to fix it. Please help me if you can.
var img = new Array();
img[0] = "https://images-na.ssl-images-amazon.com/images/I/5101NtSnx0L._AC_.jpg";
img[1] = "https://thumbor.forbes.com/thumbor/fit-in/1200x0/filters%3Aformat%28jpg%29/https%3A%2F%2Fspecials-images.forbesimg.com%2Fimageserve%2F5ecc17cdfd6d6700060f826c%2F0x0.jpg";
img[2] = "https://cdn.episode.ninja/file/episodeninja/4090819.jpg";
img[3] = "https://i.pinimg.com/564x/f0/e5/a9/f0e5a984f263b7ecb5c9cd26a493a115.jpg";
function Next() {
if (i < img.length - 1)
i++;
else
i = 0;
document.getElementById("img1").src = img[i];
}
startslideshow() {
id = window.setInterval("Next()", 1000);
var x = document.getElementById("txt").value;
id2 = window.clearTimeout("Cancel()", x * 1000)
}
<body>
<img id="img1" height="300" width="300" src="https://2.bp.blogspot.com/-ho7KT0UEARE/VPbiU-U_KSI/AAAAAAAALVM/iZdcRS6KHvQ/s1600/Acrobatty%2BBunny%2B-%2BRobert%2BMcKimson%2B(3).jpg" /> <br>
<button id="Next" onclick="Next()"> Next </button>
<button onclick="startslideshow()">startSlideShow</button>
</body>
here is the solution that we have came up with
<body>
<img id="img1" height="300" width="300" src="https://2.bp.blogspot.com/-ho7KT0UEARE/VPbiU-U_KSI/AAAAAAAALVM/iZdcRS6KHvQ/s1600/Acrobatty%2BBunny%2B-%2BRobert%2BMcKimson%2B(3).jpg" /> <br>
<button id="Next" onclick="Next()"> Next </button>
<button onclick="startslideshow()">startSlideShow</button>
<button onclick="stopslideshow()">stopSlideShow</button>
</body>
var img = new Array();
var cur = 0;
var timer = null;
img[0] = "https://images-na.ssl-images-amazon.com/images/I/5101NtSnx0L._AC_.jpg";
img[1] = "https://thumbor.forbes.com/thumbor/fit-in/1200x0/filters%3Aformat%28jpg%29/https%3A%2F%2Fspecials-images.forbesimg.com%2Fimageserve%2F5ecc17cdfd6d6700060f826c%2F0x0.jpg";
img[2] = "https://cdn.episode.ninja/file/episodeninja/4090819.jpg";
img[3] = "https://i.pinimg.com/564x/f0/e5/a9/f0e5a984f263b7ecb5c9cd26a493a115.jpg";
function Next() {
cur = (cur < img.length - 1) ? cur + 1 : 0;
document.getElementById("img1").src = img[cur];
}
function startslideshow() {
timer = setInterval(function() {
Next();
}, 500);
}
function stopslideshow() {
if (timer) {
clearInterval(timer);
timer = null;
}
}

Script code will display when click button

I'm trying to make a very, very simple image slider/slideshow with no autoplay. I only want to go to next or prev image on click. Having some issues as you can read below.
Problem : everytime I will click previous button it will display my javascript code
var backgroundImage = new Array();
backgroundImage[0] = "images/image1.jpg";
backgroundImage[1] = "images/image2.jpg";
backgroundImage[2] = "images/image3.jpg";
backgroundImage[3] = "images/image4.jpg";
backgroundImage[4] = "images/image5.jpg";
backgroundImage[5] = "images/image6.jpg";
backgroundImage[6] = "images/image7.jpg";
function displayAllImages() {
var i = 0,
len = backgroundImage.length;
for (; i < backgroundImage.length; i++) {
var img = new Image();
img.url = backgroundImage[i];
img.style.width = '160px';
img.style.height = '120px';
document.getElementById('images').appendChild(img);
}
};
displayAllImages();
$('.sp').first().addClass('active');
$('.sp').hide();
$('.active').show();
$('#button-next').click(function() {
$('.active').removeClass('active').addClass('oldActive');
if ($('.oldActive').is(':last-child')) {
$('.sp').first().addClass('active');
} else {
$('.oldActive').next().addClass('active');
}
$('.oldActive').removeClass('oldActive');
$('.sp').fadeOut();
$('.active').fadeIn();
});
$('#button-previous').click(function() {
$('.active').removeClass('active').addClass('oldActive');
if ($('.oldActive').is(':first-child')) {
$('.sp').last().addClass('active');
} else {
$('.oldActive').prev().addClass('active');
}
$('.oldActive').removeClass('oldActive');
$('.sp').fadeOut();
$('.active').fadeIn();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container" align="center">
<div id="slider-wrapper">
<div id="slider">
<div class="backgoundImage">
<ul id="images"></ul>
</div>
</div>
</div>
</div>
<div id="container">
<hr>
<div id="nav" align="center">
<div id="button-previous">
<input id="prev_btn" type="button" name="prev_btn" value="Previous">
</div>
<div id="button-next">
<input id="next_btn" type="button" name="next_btn" value="Next">
</div>
</div>
in this case, I want to ask if how can I add div tag with a class=sp and inside of it is the img tag.
Use image.src instead of image.url and to add image in div, First create div, set attribute you want and append image in div
var div = document.createElement('div');
div.setAttribute('class', 'sp');
var img = new Image();
img.src = backgroundImage[i]; // img.url = backgroundImage[i];
img.style.width = '160px';
img.style.height = '120px';
div.appendChild(img); // Append Image in Div
After that use
document.getElementById('images').appendChild(div);
Or use like that
$('#images').append('<div class="sp"><img src="' + backgroundImage[i] + '" width="160px" height="120px" /></div>');
The problem is here:
for (; i < backgroundImage.length; i++) {
var img = new Image();
img.url = backgroundImage[i];
img.style.width = '160px';
img.style.height = '120px';
// //document.getElementById('images').appendChild(img);
document.write("<div class=sp><img src='" + backgroundImage[i] + "' width='160' height='120'/></div>");
}
First: in your for loop i ssuggest initializing i inside the for loop (but is optional):
for (var i =0; i < backgroundImage.length; i++) {
Second: document.write(...);
The write() method will replace the whole content of your document. Besides, it's inside a for loop, then, you are replacing the whole document with every iteration.
You should use the other approach: appendChild(). appendChild doesn't overwrite your document, it just adds an element inside another.
Try with appendChild, if you have more questions, update your questions or post a comment.

Multiple progress bars visualy update only one

i'm working on my JavaScript skills and this is my first program trial here.
Everything was going quite well for me, but i'm stuck on this problem for about 3 days now and i guess there is something i don't get over here.
Well, diving in - i have 2 separate "Training Fields" - each has it's own "Train" button (onclick function) , "Level up" button (onclick function) and progress bar.
The problem is that the higher "Training Field" will progress the lower progress bar and not it's own.
Help will be appreciated! thx
//ignore this line, it's for me for testing
document.getElementById('hideMe').style.visibility = 'hidden';
/*========================================
Javascript for first set
========================================*/
var bodyTotal = 0;
var totalBodyCost = 0;
var bodyCost = 100;
var amountLoaded = 1;
function buyBody(){
bodyCost = totalBodyCost + Math.floor(100 * Math.pow(1.1,bodyTotal));
if(amountLoaded >= bodyCost){
totalBodyCost += bodyCost;
bodyTotal = bodyTotal + 1;
document.getElementById('bodyTotal').innerHTML = bodyTotal;
var finalMessage = document.getElementById('bodyFinalMessage').style.visibility = 'hidden';
amountLoaded = 0;
};
var nextCost = totalBodyCost + Math.floor(100 * Math.pow(1.1,bodyTotal));
document.getElementById('bodyCost').innerHTML = nextCost;
document.getElementById("bodyProgressBar").max = nextCost;
bodyCost = nextCost;
progressBarSim(amountLoaded);
};
function progressBarSim(al) {
var bar = document.getElementById('bodyProgressBar');
var status = document.getElementById('bodyStatus');
status.innerHTML = al+"/" +bodyCost;
bar.value = al;
al++;
var sim = "progressBarSim("+al+")";
}
function trainBody(){
progressBarSim(amountLoaded);
if(amountLoaded < bodyCost){
amountLoaded++;
}else{
var finalMessage = document.getElementById('bodyFinalMessage').style.visibility = 'visible';
finalMessage.innerHTML = "";
}
};
/*=============================================*/
/*========================================
Javascript for second set
========================================*/
var mindTotal = 0;
var totalMindCost = 0;
var mindCost = 100;
var amountLoaded = 1;
function buyMind(){
mindCost = totalMindCost + Math.floor(100 * Math.pow(1.1,mindTotal));
if(amountLoaded >= mindCost){
totalMindCost += mindCost;
mindTotal = mindTotal + 1;
document.getElementById('mindTotal').innerHTML = mindTotal;
var finalMessage = document.getElementById('mindFinalMessage').style.visibility = 'hidden';
amountLoaded = 0;
};
var nextCost = totalMindCost + Math.floor(100 * Math.pow(1.1,mindTotal));
document.getElementById('mindCost').innerHTML = nextCost;
document.getElementById("mindProgressBar").max = nextCost;
mindCost = nextCost;
progressBarSim(amountLoaded);
};
function progressBarSim(al) {
var bar = document.getElementById('mindProgressBar');
var status = document.getElementById('mindStatus');
status.innerHTML = al+"/" +mindCost;
bar.value = al;
al++;
var sim = "progressBarSim("+al+")";
}
function trainMind(){
progressBarSim(amountLoaded);
if(amountLoaded < mindCost){
amountLoaded++;
}else{
var finalMessage = document.getElementById('mindFinalMessage').style.visibility = 'visible';
finalMessage.innerHTML = "";
}
};
/*=============================================*/
<html>
<head>
<link rel="stylesheet" type="text/css" href="interface.css" />
</head>
<body>
<div style="float:right">
Body Level: <span id="bodyTotal">0</span>
<button onclick="trainBody()">Train Body</button><br>
<progress id="bodyProgressBar" value="0" max="100" style="width:200px; float:left;"></progress>
<span id="bodyStatus" style="float:left; z-index:555; margin-left:-110px;">0/100</span>
<button id="bodyFinalMessage" style="float:left; visibility:hidden" onclick="buyBody()">Body Level Up</button>
<br><br>
Mind Level: <span id="mindTotal">0</span>
<button onclick="trainMind()">Train Mind</button><br>
<progress id="mindProgressBar" value="0" max="100" style="width:200px; float:left;"></progress>
<span id="mindStatus" style="float:left; z-index:555; margin-left:-110px;">0/100</span>
<button id="mindFinalMessage" style="float:left; visibility:hidden" onclick="buyMind()">Mind Level Up</button>
</div>
<div id="hideMe" style="position:absolute; top:400; left:400">
Body Cost: <span id="bodyCost">100</span><br>
Mind Cost: <span id="mindCost">100</span>
</div>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
You are reassigning variables and functions using the exact same names amountLoaded, progressBarSim(al).
Because body and mind behavior are very similar you could use a module pattern (http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html) to use the same variable and function names within their own scopes.
<button onclick="Body.onClick()">Body</button>
<button onclick="Mind.onClick()">Mind</button>
And in your script file
var Body = (function() {
var me = {};
me.onClick = function() {
console.log("body click");
progressBar(al);
};
function progressBar(al) {
}
return me;
})();
var Mind = (function() {
var me = {};
me.onClick = function() {
console.log("mind click");
progressBar(al);
};
function progressBar(al) {
}
return me;
})();
The gotcha here is you can't use body with the inline onclick since that already refers to the body element.

How to choose one image out of three? The rest has to be invisible

I'am making a game. You can choose one bokser out of three as your own bokser. Than you can choose the enemy, also one image out of three. After you choose your own bokser and the enemy. Both images has to be visible the rest invisible.
This is my HTML
<div id="jouwbokser">
<h1>Kies Jouw Bokser!</h1>
<img id="bokser1" src="img/bokser1.png" alt="bokser" /><!--Bron:proksa.pl-->
<img id="boker2" src="img/bokser2.png" alt="bokser2" /><!--Bron:www.weekendowo.pl-->
<img id="bokser3" src="img/bokser3.png" alt="bokser3" /><!--Bron:www.ufc.com-->
</div>
<div id="computer">
<h1>Kies je Tegenstander</h1>
<img id="bokser4" src="img/bokser1.png" alt="bokser" /><!--Bron:proksa.pl-->
<img id="bokser5" src="img/bokser2.png" alt="bokser2" /><!--Bron:www.weekendowo.pl-->
<img id="bokser6" src="img/bokser3.png" alt="bokser3" /><!--Bron:www.ufc.com-->
</div>
Has anyone an idea how?
https://jsfiddle.net/o7m1w2qk/
There is a huge amount of how to do this. It's all depend on your requirements, environment, browsers support, whatever.
For example using jQuery:
$("img").on("click", function() {
var $this = $(this);
var $div = $this.parent();
$div.addClass("has-selected");
$("img", $div).removeClass("selected");
$this.addClass("selected");
});
CSS:
#jouwbokser.has-selected > img:not(.selected),
#computer.has-selected > img:not(.selected) {
display: none;
}
https://jsfiddle.net/o7m1w2qk/1/
UPDATE
Non jQuery solution:
var onclickImg = function(event) {
var img = event.target;
var div = img.parentElement;
for (var i = 0; i < div.children.length; i++) {
var child = div.children[i];
if (child.nodeName != "IMG") {
continue;
}
child.className = "";
}
div.className = "has-selected";
img.className = "selected";
}
imgs = document.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
imgs[i].addEventListener('click', onclickImg);
}
https://jsfiddle.net/o7m1w2qk/3/

What's wrong with this code to move css elements with javascript?

I am trying to move an element with javascript. I searched for a while and I think that this code should do the trick... but it does not, and I get no errors in the Console... anybody can help?
<html><body>
<script>
function move1(){
var cusid_ele = document.getElementsByClassName('zzz');
for (var i = 0; i < cusid_ele.length; ++i) {
var item = cusid_ele[i];
var x=item.style.top;
x+=10;
item.style.top=x;
}
}
function move2(){
var cusid_ele = document.getElementsByClassName('zzz');
for (var i = 0; i < cusid_ele.length; ++i) {
var item = cusid_ele[i];
var x=item.style["top"];
x+=10;
item.style["top"]=x;
}
}
function move3(){
var cusid_ele = document.getElementsByClassName('zzz');
for (var i = 0; i < cusid_ele.length; ++i) {
var item = cusid_ele[i];
var x=item.style["top"];
x+=10;
item.style["top"]=x+'px';
}
}
</script>
<input type=button onclick="move1();" value="Move (1st way, with .top=x)!">
<input type=button onclick="move2();" value="Move (2nd way, with [top]=x)!">
<input type=button onclick="move3();" value="Move (3rd way, with [top]=xpx)!">
<h3 class=zzz >Move me! (no inline style)</h3>
<h3 class=zzz style="top: 50px;">Move me! (with inline style)</h3>
</body></html>
By the way, I tried both FF and Chrome...
-- Accepted solution, I write it here so one can have a working example (thank you Adeneo!):
<script>
function move1(){
var cusid_ele = document.getElementsByClassName('zzz');
for (var i = 0; i < cusid_ele.length; ++i) {
var item = cusid_ele[i];
var x = parseInt( item.style.top, 10 );
x+=10;
item.style.top=x+'px';
}
}
</script>
<input type=button onclick="move1();" value="Move!">
<h3 class=zzz >I cant move! (no css positioning)</h3>
<h3 class=zzz style="position: relative; top: 50px;">I can move! (with css positioning)</h3>
</body></html>
This
var x=item.style["top"];
returns the string 300px etc, so
x += 10;
ends up being
300px10
so replace
var x=item.style.top;
with
var x = parseInt( item.style.top, 10 );
the same goes for setting styles
element.style.top = x + 'px';
You'll have to use a string with units, and to make the CSS actually do something, the elements must be positioned
FIDDLE

Categories

Resources