JavaScript change img src - javascript

I am trying to make an image slider just using JavaScript. I have a button with an id in HTML and want to change the src of the button based on a position in an array. This is my following code.
var index = 0;
var imageArray = [{'images/img1.jpg'},{'images/img2.jpg'},{'images/img3.jpg'},{'images/img4.jpg'}];
function moveToNextSlide()
{
if (index >= imageArray.length -1)
{
index =-1;
}
var img = getElementById(img_start);
index = index + 1;
var currentSlide = imageArray[index];
getElementByid(img_start).src="currentSlide";
}

Looks like you're trying to create an array of strings. You have:
var imageArray = [{'images/img1.jpg'},{'images/img2.jpg'},{'images/img3.jpg'},{'images/img4.jpg'}];
Braces ({}) are used to declare objects; the braces you have around each string are a syntax error. For just an array of strings, simply leave the quoted literals without braces:
var imageArray = ['images/img1.jpg','images/img2.jpg','images/img3.jpg','images/img4.jpg'];

There are a few issues. Firstly, you need to use the correct array syntax.
var imageArray = ['images/img1.jpg','images/img2.jpg','images/img3.jpg','images/img4.jpg'];
Also, you need to use document.getElementById and set as getElementById on it's own will refer to the window, not the document.
Finally, you need to set to the variable currentSlide like so img.src= currentSlide;, not "currentSlide" as a string.
function moveToNextSlide(){
if (index >= imageArray.length -1){
index =-1;
}
var img = document.getElementById('img_start');
index = index + 1;
var currentSlide = imageArray[index];
img.src= currentSlide;
}
See full example here
var index = 0;
var imageArray = ['http://www.profightdb.com/img/wrestlers/thumbs-600/1414330df8brethart.jpg', 'http://armpit-wrestling.com/wp-content/uploads/2016/06/bret-hart.jpg'];
document.body.onload = function(){
document.getElementById('img_start').src = imageArray[0];
};
function moveToNextSlide() {
if (index >= imageArray.length - 1) {
index = -1;
}
var img = document.getElementById('img_start');
index = index + 1;
var currentSlide = imageArray[index];
img.src = currentSlide;
}
img {
max-width: 100px;
}
p {
cursor: pointer;
}
<img id="img_start" src="">
<p onclick="moveToNextSlide()">Click Here</p>

Related

How to set src to each shuffled image in javascript?

I'm trying to shuffle images from array to a specific div.
<body>
<div id="set"></div>
</body>
<script>
var ArrayOfImages = ['bar.jpg',
'foo.jpg',
'koo.jpg',
'too.jpg'
];
var set = document.getElementById("set");
set.addEventListener("click", randomize, false);
ArrayOfImages.forEach(function(image) {
var elem = document.createElement('img');
elem.src = image;
set.appendChild(elem);
});
function shuffle(array) {
let counter = array.length;
// While there are elements in the array`enter code here`
while (counter > 0) {
// Pick a random index
let index = Math.floor(Math.random() * counter);
// Decrease counter by 1
counter--;
// And swap the last element with it
let temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}
return array;
}
function randomize() {
set.innerHTML = shuffle(ArrayOfImages);
}
</script>
Now the problem is, that innerHTML only changes the text of the image but cannot set an src to it. Though it does the shuffle.
Any help would be appreciated!
.innerHTML will change the actual HTML, not the images src which is what you want to change.
At the moment you are getting your image elements from your HTML using
document.getElementById('set)
however, you HTML can only have one element with the id set. Thus, you can use the class attribute instead to give multiple elements the identifier of 'set' and get all your image elements using:
document.getElementsByClassName('set')
which will return a collection of your HTML image tags. Now, to change each image's source you can loop over this collection or loop over your shuffled images and set each image's source.
See an example below for further clarification:
var img_elems = document.getElementsByClassName('set'); // Get all elements to set the image to
// To go into your randomize() function:
// Shuffled images returned via your shuffle() function
var shuffled_images = ['https://images.pexels.com/photos/34950/pexels-photo.jpg?auto=compress&cs=tinysrgb&h=350', 'https://www.pandotrip.com/wp-content/uploads/2018/09/Seigantoji-Pagoda-and-Nachi-Falls-in-Nacho-Japan.jpg', 'https://www.elastic.co/assets/bltada7771f270d08f6/enhanced-buzz-1492-1379411828-15.jpg'];
for (var i = 0; i < shuffled_images.length; i++) {
img_elems[i].src = shuffled_images[i]; // Set the image to the src value.
}
/* Ignore this */
img {
height: 200px;
width: 200px;
}
<img src="" class="set" /><br />
<img src="" class="set" /><br />
<img src="" class="set" />
More clean and better way of doing it in vanilla javascript.
The issue was in your shuffle function.
var image_swap_tool = function(options){
var self = this;
self.ArrayOfImages = options.ArrayOfImages;
self.image_container_elem = document.getElementById("set");
self.image_container_elem.addEventListener("click", function(){
self.randomize();
});
}
image_swap_tool.prototype.create_image = function(){
var self = this;
var images = self.ArrayOfImages;
var image_container = self.image_container_elem;
image_container.innerHTML = '';
for(var i=0; i < images.length;i++){
var img = document.createElement('img');
img.setAttribute('src',images[i]);
image_container.appendChild(img);
}
};
image_swap_tool.prototype.shuffle = function(){
var self = this;
var images = self.ArrayOfImages;
let counter = images.length;
while (counter > 0) {
// Pick a random index
let index = Math.floor(Math.random() * counter);
// Decrease counter by 1
counter--;
// And swap the last element with it
let temp = images[counter];
images[counter] = images[index];
images[index] = temp;
}
//Set new order back to images for next time
self.ArrayOfImages = images;
//Images are shuffled then append them again
self.create_image();
}
image_swap_tool.prototype.randomize = function(){
var self = this;
var image_container = self.image_container_elem;
self.shuffle();
}
var options = {};
options.ArrayOfImages = ['bar.jpg', 'foo.jpg', 'koo.jpg', 'too.jpg'];
var tool = new image_swap_tool(options);
tool.create_image();
Thanks

I don't how why my backgroundImage doesn't work

Why does my banner doesn't change her background? Please help me.
When I run the file the console tells me:
Uncaught TypeError: flechedroite.addEventListener is not a function
I really don't understand. I'm a beginner in Javascript so please explain me with kind words how I can fix this error :)
var flechedroite = document.getElementsByClassName('fa-arrow-right');
var flechegauche = document.getElementsByClassName('switch-left');
var banner = document.getElementById('banner');
var images = [];
var changeBackground = function (bElement, bUrl) {
return bElement.style.backgroundImage = "url(" + bUrl + ")";
}
//image list
images[0] = 'images/image1.jpg';
images[1] = 'images/image2.jpg';
images[2] = 'images/image3.jpg';
flechedroite.addEventListener('click', function() {
for (var i = 0; i < images.length; i++) {
changeBackground(document.body, images[i]);
}
})
addEventListener should be called in window.onload or in $(document).ready()
Since getElementsByClassName returns an array, you need to use array index with flechedroite to add an event listener. i.e. flechedroite[0].addEventListener('click', function() {...});
You are calling changeBackground function in a loop to set the background image, effectively you will see only the last image from the array being set as background.
JS Code
var images = [];
var changeBackground = function (bElement, bUrl) {
return bElement.style.backgroundImage = "url("+bUrl+")";
}
//image list
images[0] = 'https://www.gettyimages.ie/gi-resources/images/Homepage/Hero/UK/CMS_Creative_164657191_Kingfisher.jpg';
images[1] = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTOGUhZo0Qe81U5qY_Z-seXgsD79LEEet832TVOlLMOEy10ZPsV';
images[2] = 'https://cdn.pixabay.com/photo/2016/06/18/17/42/image-1465348_960_720.jpg';
window.onload = function(){
var flechedroite = document.getElementsByClassName('fa-arrow-right');
var flechegauche = document.getElementsByClassName('switch-left');
var banner = document.getElementById('banner');
var currentImageIndex = 0;
flechedroite[0].addEventListener('click', function() {
currentImageIndex = (currentImageIndex+1)%images.length;
changeBackground(document.body, images[currentImageIndex]);
})
}
The function getElementsByClassName returns a HTMLCollection, which is an array like structure that can contain multiple elements. So you need to use an index to access the elements contained in it.
So flechedroite.addEventListener results in an error but flechedroite[0].addEventListener should work
https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByClassName
if you use 'getElementsByClassName' and you want to add an 'addEventListener', you can not do it in a 'generic' way: "flechedroite.addEventListener ('click', function () {}". You have to do this for each element:
var flechedroite = document.getElementsByClassName('fa fa-arrow-right');
//flechedroite contains all the elements that have the 'fa fa-arrow-right' classes
//on each element you have to add the "addEventListener"
for (var i = 0; i < flechedroite.length; i++) {
flechedroite[i].addEventListener('click', function() {
alert('flechedroite');
});
}
basic example JSFiddle1
a more advanced example
JSFiddle2

Replace all img src on page load - Javascript

I'm trying to replace all img src's on my page, when they have a certain url in them. So far I'm able to log all the replaced img src's, but my final step would be to change them on my page.
function replaceMyImgs() {
// put live url here
var liveUrl = "via.placeholder.com";
// find the local url
var localUrl = "testdomain.com";
// replace the local url for the live url
var newUrl = localUrl.replace(/testdomain.com/g, liveUrl);
// console.log(newUrl);
// get all images and push them in an empty array
var imgs = document.getElementsByTagName("img");
var imgSrcs = [];
for (var i = 0; i < imgs.length; i++) {
imgSrcs.push(imgs[i].src);
}
imgSrcs.forEach(function(src) {
// log all the found img srcs
var newSrc = src.replace(/testdomain.com/g, liveUrl);
imgs.src = newSrc;
console.log(imgs.src);
});
}
window.onload = replaceMyImgs;
See my pen: https://codepen.io/kleefaan/pen/yqzBVv
Instead of pushing all elements into an array you can do the replace in the for loop like this:
// get all images
var imgs = document.getElementsByTagName("img");
for (var i = 0; i < imgs.length; i++) {
var newSrc = imgs[i].src.replace(/testdomain.com/g, liveUrl);
imgs[i].src = newSrc;
console.log(imgs[i].src);
}

Change 2 image each other when click on them

i have a div with multiple images inside and i need to click on a random image then again click on a random picture and when i clicked the second image to change images with each other. All images are interchangeable.Heres what i've done so far:
EDIT FIDDLE: http://jsfiddle.net/w53Ls/5/
$("#image1").click(function(){
imagePath = $("#image2").attr("src");
if(imagePath == "http://s15.postimg.org/oznwrj0az/image.jpg"){
$("#image3").attr("src", "http://s21.postimg.org/ojn1m2eev/image.jpg");
}else{
$("#image4").attr("src", "http://s23.postimg.org/epckxn8uz/image.jpg");
}
});
EDIT: The code i have tryed for check function is in EDIT FIDDLE and with the alert i check src of pictures.Now i simply need to make a condition to alert something after i change all the pieces in order and found the whole picture.Any hint?
DEMO
var clickCount = 0;
var imgSrc;
var lastImgId;
$("img.element").click(function(){
if (clickCount == 0)
{
imgSrc = $(this).attr("src");
lastImgId = $(this).attr("id");
clickCount++;
}
else {
$("#"+lastImgId).attr("src",$(this).attr("src"));
$(this).attr("src",imgSrc)
clickCount = 0;
}
});
Updated
This let's you know when you're done with the puzzle
DEMO
var clickCount = 0;
var imgSrc;
var lastImgId;
// Function for Comparing Arrays
// source: http://stackoverflow.com/questions/7837456/
Array.prototype.compare = function (array) {
if (!array) return false;
if (this.length != array.length) return false;
for (var i = 0, l = this.length; i < l; i++) {
if (this[i] instanceof Array && array[i] instanceof Array) {
if (!this[i].compare(array[i])) return false;
} else if (this[i] != array[i]) {
return false;
}
}
return true;
}
$(document).ready(function () {
// Store the correct order first in an array.
var correctOrder = $("#puzzle > img").map(function () {
return $(this).attr("src");
}).get();
// Randomize your images
var a = $("#puzzle > img").remove().toArray();
for (var i = a.length - 1; i >= 1; i--) {
var j = Math.floor(Math.random() * (i + 1));
var bi = a[i];
var bj = a[j];
a[i] = bj;
a[j] = bi;
}
$("#puzzle").append(a);
$("img.element").click(function () {
if (clickCount == 0) {
imgSrc = $(this).attr("src");
lastImgId = $(this).attr("id");
clickCount++;
} else {
$("#" + lastImgId).attr("src", $(this).attr("src"));
$(this).attr("src", imgSrc);
clickCount = 0;
// Get the current order of the images
var currentOrder = $("#puzzle > img").map(function () {
return $(this).attr("src");
}).get();
// Compare the current order with the correct order
if (currentOrder.compare(correctOrder)) alert("Puzzle completed");
}
});
});
http://jsfiddle.net/w53Ls/2/
var counter = 0;
The code was improvised but works XD
you try improve it
Here is a new version of your jsfiddle that I think will do what you want.
It applies the same click handler to every object with the class swapable. Each time a swapable element is clicked, the handler checks whether another element was previously clicked first. If so, it swaps them. If not, it just remembers that this element is the first one.
var firstId = ''; // Initially, no element has been clicked first
var firstSrc = '';
// Apply the following function to every element with 'class="swapable"
$('.swapable').click(function(){
if (firstId !== '') { // There is already a first element clicked
// Remember the information of the currently clicked element
var secondId = $(this).attr('id');
var secondSrc = $(this).attr('src');
// Replace the currently clicked element with the first one
$('#' + secondId).attr('src', firstSrc);
// Replace the first one with the current one
$('#' + firstId).attr('src', secondSrc);
// Forget the first one, so that the next click will produce a new first
firstId = '';
firstSrc = '';
}
else // This is the first element clicked (this sequence)
{
// Remember this information for when a second is clicked
firstId = $(this).attr('id');
firstSrc = $(this).attr('src');
}
});

How to sort a random div order in jQuery?

On page load, I am randomizing the order of the children divs with this Code:
function reorder() {
var grp = $("#team-posts").children();
var cnt = grp.length;
var temp, x;
for (var i = 0; i < cnt; i++) {
temp = grp[i];
x = Math.floor(Math.random() * cnt);
grp[i] = grp[x];
grp[x] = temp;
}
$(grp).remove();
$("#team-posts").append($(grp));
}
I cannot seem to figure out how to get the posts back in the original order. Here's the demo of my current code http://jsfiddle.net/JsJs2/
Keep original copy like following before calling reorder() function and use that for reorder later.
var orig = $("#team-posts").children();
$("#undo").click(function() {
orderPosts();
});
function orderPosts() {
$("#team-posts").html( orig ) ;
}
Working demo
Full Code
var orig = $("#team-posts").children(); ///caching original
reorder();
$("#undo").click(function(e) {
e.preventDefault();
orderPosts();
});
function reorder() {
var grp = $("#team-posts").children();
var cnt = grp.length;
var temp, x;
for (var i = 0; i < cnt; i++) {
temp = grp[i];
x = Math.floor(Math.random() * cnt);
grp[i] = grp[x];
grp[x] = temp;
}
$(grp).remove();
$("#team-posts").append($(grp));
}
function orderPosts() {
// set original order
$("#team-posts").html(orig);
}
How about an "undo" plugin, assuming it applies?
Just give each item a class with the corresponding order and then get the class name of each div and save it to a variable
$("#team-posts div").each(function() {
var parseIntedClassname = parseInt($(this).attr("class");
arrayName[parseIntedClassname] = $("#team-posts div." + parseIntedClassname).html()
});
You can reorder them from there by saving their html to an array in order
$("#team-posts").html();
for(var i=0;i<arrayName.length;i++){
$("#team-posts").append('<div class="'+i+'">'+arrayName[i]+'</div>');
}
The solution with saving away the original order is probably the best but if you have to dynamically sort it, you can use this:
http://www.w3schools.com/jsref/jsref_sort.asp
function orderPosts() {
var $grp = $("#team-posts"),
ordered = $grp.children().toArray().sort(function(a, b) {
return parseInt($(a).text()) > parseInt($(b).text());
});
$grp.empty().append(ordered);
}

Categories

Resources