Script code will display when click button - javascript

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.

Related

Having trouble with displaying an image through an array

I am practicing with JavaScript Array function. What I want to achieve is to show google embedded images inside the display section when the user clicks "Show my grocery list" button after entering "banana", else the texts will be shown instead.
These are my codes.
var grocery = document.getElementById("grocery");
let showItems = document.getElementById("showItems");
const display = document.getElementById("display");
var groceryList = [];
grocery.addEventListener("keyup",function(ev){
if(ev.keyCode == 13){
groceryList.push(grocery.value);
console.log("array",groceryList);
}
});
showItems.addEventListener("click",function(){
for (var i = 0; i < groceryList.length;i++){
if(groceryList[i] == "banana"){
display.src = "https://i5.walmartimages.ca/images/Enlarge/271/747/6000191271747.jpg";
} else {
display.innerHTML += groceryList[i] + "<br/>";
}
}
});
#display {
width:100px;
height:100px;
}
<div id="controls">
<input type="text" placeholder="grocery items" id="grocery"/>
<button id="showItems">Show My Grocery List</button>
</div>
<div id="display"></div>
It is currently not showing anything. I have a feeling that I have written a wrong syntax inside the loop function? I would appreciate a solution and tips. Thank you.
You've to remove the keyCode=13 condition first and then need to create an img element with src of image based on condition (groceryList[i] == "banana") to display the image inside the <div> element, For example:
var grocery = document.getElementById("grocery");
let showItems = document.getElementById("showItems");
const display = document.getElementById("display");
var groceryList = [];
grocery.addEventListener("keyup", function(ev) {
//if(ev.keyCode == 13){
groceryList.push(grocery.value);
//console.log("array",groceryList);
//}
});
showItems.addEventListener("click", function() {
for (var i = 0; i < groceryList.length; i++) {
if (groceryList[i] == "banana") {
var source = "https://i5.walmartimages.ca/images/Enlarge/271/747/6000191271747.jpg";
var img = document.createElement("IMG"); //create img element
img.src = source; //set img src
display.appendChild(img); // display image inside <div>
} else {
display.innerHTML += groceryList[i] + "<br/>";
}
}
});
<div id="controls">
<input type="text" placeholder="grocery items" id="grocery" />
<button id="showItems">Show My Grocery List</button>
</div>
<div id="display"></div>

Jquery How To Stop Append from Appending Previous Element

I'm having trouble to display the star of each hotel and not sure on how to do it. I have like 5 hotels, and each has different value of hotelStar.
My Javascript code:
function GetStarHotel() {
var parent = $(' p.star '),
imagePath = 'image/hotelstar.png',
img;
for (var i = 0; i < hotelStar; i++) {
img = new Image();
img.src = imagePath;
$(parent).append('<img src="image/hotelstar.png" class="hotelStar" />')
}
}
And my HTML Code is:
<h1>Hotel 1</h1>
<p class="star"><script>
hotelStar = 4;
GetStarHotel();
</script></p>
<h1>Hotel 2</h1>
<p class="star"><script>
hotelStar = 3;
GetStarHotel();
</script></p>
<h1>Hotel 3</h1>
<p class="star"><script>
hotelStar = 2;
GetStarHotel();
</script></p>
It is adding my previous Hotel's Stars. How can I prevent it from adding the same element?
Instead of append() you can use .html(), check updated code below
function GetStarHotel() {
var parent = $(' p.star '),
imagePath = 'image/hotelstar.png',
img,
star = '';
for (var i = 0; i < hotelStar; i++) {
img = new Image();
img.src = imagePath;
star += '<img src="'+imagePath +'" class="hotelStar" />';
}
$(parent).html(star)
}
i have simplified your code. check updated snippet below
$('p.star').each(function(){
count = $(this).data('star'),
star = '',
imagePath = 'http://www.freeiconspng.com/uploads/download-png-image-star-png-image-1.png';
for (var i = 0; i < count; i++) {
star += '<img src="'+imagePath +'" width="16" class="hotelStar" alt="'+i+'" />';
}
$(this).html(star)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Hotel 1</h1>
<p class="star" data-star ="4" ></p>
<h1>Hotel 2</h1>
<p class="star" data-star ="3"></p>
<h1>Hotel 3</h1>
<p class="star" data-star ="2"></p>

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/

Javascript - Resizing Slideshow Images

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

Select top 3 values from variable, then next 3 etc

I have this variable with images. I also have 3 div's in which I want to put the images.
var images = [
'dali.jpg',
'illusionisme.png',
'impresionisme.jpg',
'popart.jpg',
'abstracter.jpg',
'abstrat.jpg',
'concept.jpg',
'fingerpaint.jpg',
'flowers.jpg',
'graffiti.jpg',
'groovy.jpg',
'skelly.jpg',
'vangogh.jpg'
]
By using this code every div does get a random image, which is nice but not what I want. How can I use jQuery to put the first 3 images inside the 3 divs, then the second 3 images in the div?
$(".art").click(function(){
$(".art").each(function(){
$(this).find("img").remove();
$(this).prepend('<img src="assets/images/' + images[Math.floor(Math.random()*images.length)] + '">');
});
});
<div class="art">
<div class="art">
<div class="art">
Not sure what you mean, please elaborate if this is not what you are looking for..
http://jsfiddle.net/jFIT/c7U7q/1/
where the code is giving just text now, you can wrap that text in an <img src= /> to give you the images..
var images = [
'dali.jpg',
'illusionisme.png',
'impresionisme.jpg',
'popart.jpg',
'abstracter.jpg',
'abstrat.jpg',
'concept.jpg',
'fingerpaint.jpg',
'flowers.jpg',
'graffiti.jpg',
'groovy.jpg',
'skelly.jpg',
'vangogh.jpg'];
$(".art").click(function () {
$(this).html(getNext3()); //images[Math.floor(Math.random()*images.length)]);
});
$('#startLoop').click(function () {
loopImages();
});
function loopImages(){
var art = $('.art');
art.fadeOut(1000, function () {
art.html(getNext3()).fadeIn(1000, function() { loopImages(); });
});
}
var counter = 0;
function getNext3() {
var imgs = "";
//img src=...
for (i = 0; i < 3; i++) {
imgs += ' ' + images[counter];
counter++;
}
return imgs;
}
UPDATED
(load 3 into 3 divs at a time.)
http://jsfiddle.net/jFIT/c7U7q/7/
function setNext3() {
var imgs = "";
//img src=...
for (i = 0; i < 3; i++) {
imgs = images[counter];
console.log(imgs);
console.log(i);
$("div.art:nth-child(" + (i + 1) + ")").html(imgs);
console.log($("div.art:nth-child(" + i + ")"));
counter++;
}
}
You can keep track of the current image index and then add the number to increase the index by each click
html
<div class="art">
<img data-imageindex="0" src="" />
</div>
<div class="art">
<img data-imageindex="1" src="" />
</div>
<div class="art">
<img data-imageindex="2" src="" />
</div>
js
var artLength = $(".art").length;
$(".art").click(function () {
$(".art").each(function () {
var $image = $(this).find("img");
var nextImageIndex = $image.data("imageindex") + artLength;
if (nextImageIndex >= images.length) {
nextImageIndex -= images.length;
}
$image.data("imageindex", nextImageIndex).attr("src",
"assets/images/" + images[nextImageIndex]);
});
});
http://jsfiddle.net/44zB4/

Categories

Resources