How do you use increments? - javascript

I am not sure how to use increments.
through a function. i can't get the paragraph to show the array words
<p id= "demo"
var Array = ["hello", "goodbye"];
var mimg = document.getElementById(imageArray[0]);
mimg.setAttribute('src', [index]);
//var ArrayIndex = 0;
function change() {
("src", Array[Index]);
imageIndex++;
if (Index >= Array.length) {
Index = 0;
}
}

Don't forget to use your browser's console, read this article Using Your Browser to Diagnose JavaScript Errors.
Don't use setattribute function, use src attribute.
var myImage = document.getElementById("mainImage");
var imageArray = ["http://lorempixel.com/400/200/sports/1/", "http://lorempixel.com/400/200/sports/2/", "http://lorempixel.com/400/200/sports/3/", "http://lorempixel.com/400/200/sports/4/"];
myImage.src = imageArray[0];
var imageIndex = 0;
function changeImage() {
myImage.src = imageArray[imageIndex];
imageIndex++;
if (imageIndex >= imageArray.length)
imageIndex = 0;
}
window.onload = function() {
setInterval(function() {
changeImage();
}, 1000);
};
<img id="mainImage" />

var myImage = document.getElementById("mainImage");
var imageArray = ["images/1.png","images/2.png","images/3.png","images/4.png"];
var mimg=document.getElementById(imageArray[0]);
mimg.setAttribute('src',photos[index]);
You aren't showing your relevant HTML, but I notice in this section you are getting an element with ID "images/1.png" and setting the src of that element to the value of something in photos[index]. You haven't shown how the photos array is loaded. Do you actually have an element with an ID "images/1.png"?
In your function, you set the src of the mainImage to the values in imageArray rather than the values in the photo array. That may be valid, but since that is different than what you did outside the function, I want to make sure that was intended.

I think you are talking about such solution:
var imageArr=["images/1.png", "images/2.png", "images/3.png", "images/4.png"];
$('#button'). on('click',function(){
var index=(Math.random(0,imageArr.length)*10)
$('#img').attr('src',imageArr[index])
});
Again you question is not clear, thus I think this will help you to get direction.

This should be solution if you are using plain JavaScript
var myImage = document.getElementById("mainImage"),
imageArray = ["images/1.png", "images/2.png", "images/3.png", "images/4.png"],
imageArrayIndex = 0;
myImage.src = imageArray[imageArrayIndex++];
function changeImage () {
myImage.src = imageArray[imageArrayIndex++];
imageArrayIndex = imageArrayIndex >= imageArray.length ? 0 : imageArrayIndex;
}
Make sure that your element is defined as "img".

Here's a solution which sets a data-index attribute on the image to keep track of the selected index. This solution is compatible with down to IE8 and does not use the Jquery library. Run the code snippet below for a test (click the image to go to the next one).
var mimg = document.getElementById('main-image'),
simg = document.getElementById('sec-image')
imgArr = [
'http://placehold.it/50x50/00AAAA',
'http://placehold.it/50x50/AAAA00',
'http://placehold.it/50x50/AA00AA',
];
var loopImages = function(element, imgArray, startAt) {
var index = element.getAttribute('data-index'),
newIndex = 0;
if (!index)
newIndex = ((startAt && startAt < imgArr.length-1) || 0) + 1;
else if (index < imgArr.length-1)
newIndex = parseInt(index) + 1;
element.setAttribute('data-index', newIndex);
element.src = imgArr[newIndex];
};
mimg.addEventListener('click', function(e) {
loopImages(e.target || e.srcElement, imgArr);
});
setInterval(function() {
loopImages(simg, imgArr);
}, 500);
<p>Preview (click to change)</p>
<img id="main-image" src="http://placehold.it/50x50/00AAAA">
<br>
<p>Preview with interval</p>
<img id="sec-image" src="http://placehold.it/50x50/00AAAA">

Related

Background image changer interval Javascript

I'm new to javascript and I need some help with a function that I am trying to get to run. I would like for the background of my body to change every seconds using the images provided but when I try to run the script it does not seem to work.
Javascript:
var i = 0;
var images = [
URL('file:///Users/BodyDesigns/Documents/Altered%20Images/P1010216.jpg'),
URL('file:///Users/BodyDesigns/Documents/Altered%20Images/P1010217.jpg'),
URL('file:///Users/BodyDesigns/Documents/Altered%20Images/P1010200.jpg')
];
function backgroundChanger() {
for(; i < images.length; i++) {
document.getElementById('background').style.backgroundImage.innerHTML = images[i];
}
}
setInterval( backgroundChanger(), 4000);
html:
<body id="background" onLoad="backgroundChanger()">
This should do the trick.
var i = 0;
var images = [
'https://upload.wikimedia.org/wikipedia/commons/2/23/Screenshot_from_IMAX%C2%AE_3D_movie_Hidden_Universe_showing_the_Helix_Nebula_in_infrared.jpg',
'http://ichef.bbci.co.uk/wwfeatures/wm/live/1280_640/images/live/p0/40/m0/p040m0bc.jpg',
'http://az616578.vo.msecnd.net/files/2016/08/06/636060577940287734-194579614_maxresdefault.jpg'
];
function backgroundChanger() {
if(i >= images.length){
i = 0;
}
document.getElementById('background').style.backgroundImage = 'url(' + images[i++] + ')';
}
setInterval( backgroundChanger, 4000);
As you can see, the url() should be passed inside a string to work. And there is no innerHtml on backgroundImage property.

Javascript Image change onClick

I'm creating an image that changes on click. My code isn't working whats wrong with it?
<div id="img"></div>
<script>
var fNames = ["SD1", "SD2", "SD3", "SD4"]; //File names
var _img = document.getElementById("img"); //Grabs images, groups them
var imgIdx = 0;
_img.style.position = "relative";
_img.style.left = "auto";
_img.style.right = "auto";
_img.style.width = "1920";
_img.style.height = "1280";
_img.style.backgroundImage = "url('images/"+fNames[imgIdx]+".jpg')"; //Retrieves images from file
_img.addEventListener("click", onImageClick); //Allows image click
function onImageClick() {
imgIdx++;
if(imgIdx == 6) {
imgIdx = 0;
}
_img.style.backgroundImage = "url('images/"+fNames[imgIdx]+".jpg')";
}
</script>
You need a unit when you specify the size:
_img.style.width = "1920px";
_img.style.height = "1280px";
When making the index wrap around you are using 6, but it should be 5. Better yet, use the length of the array, that way you don't need to change that part of the code if the array changes:
if(imgIdx > fNames.length) {
imgIdx = 0;
}

Image gallery next button update alt from ID

I am trying to make a simple image gallery. This is what I have now:
Live demo: http://jsfiddle.net/rgvqA/
var NumberOfImages = 7;
var img = new Array(NumberOfImages);
img[0] = "http://www.kidsmathgamesonline.com/images/pictures/numbers600/number0.jpg";
img[1] = "http://www.kidsmathgamesonline.com/images/pictures/numbers600/number1.jpg";
img[2] = "http://www.kidsmathgamesonline.com/images/pictures/numbers600/number2.jpg";
img[3] = "http://www.kidsmathgamesonline.com/images/pictures/numbers600/number3.jpg";
img[4] = "http://www.kidsmathgamesonline.com/images/pictures/numbers600/number4.jpg";
img[5] = "http://www.kidsmathgamesonline.com/images/pictures/numbers600/number5.jpg";
img[6] = "http://www.kidsmathgamesonline.com/images/pictures/numbers600/number6.jpg";
var imgNumber = 0
function NextImage() {
imgNumber++;
if (imgNumber == NumberOfImages) {
imgNumber = 0;
}
document.images["largeImage"].src = img[imgNumber];
}
function PreviousImage() {
imgNumber--;
if (imgNumber < 0) {
imgNumber = NumberOfImages - 1;
}
document.images["largeImage"].src = img[imgNumber];
}
$(document).ready(function() {
$('#thumbs').delegate('img', 'click', function() {
imgNumber = $(this).attr('id');
});
});
$('#thumbs').delegate('img', 'click', function () {
$('#largeImage').attr('src', $(this).attr('src').replace('thumb', 'large'));
$('#description').html($(this).attr('alt'));
});
The problem: When I click the next and previous buttons, the alt text for the description does not change accordingly. It only does when I click the thumbnail.
How do I update the alt text to whatever image is currently displayed?
The image caption isn't getting set with the arrow button clicks, because the functions they call (NextImage and PreviousImage) do not have any code which updates it.
You can use imgNumber to retrieve the correct thumb image, get it's alt text, and update the description element with it:
$('#description').html($('#'+imgNumber).attr('alt'));
This causes because of your code ( $('#description').html($(this).attr('alt')); ) Where this refers to the small thumb. So you are getting the alt text from the thumb.
Try to crete the description in an array like above you did for images.
var desc = new Array(NumberOfImages);
`desc[0] = "http://www.kidsmathgamesonline.com/images/pictures/numbers600/number0.jpg";
desc[1] = "http://www.kidsmathgamesonline.com/images/pictures/numbers600/number1.jpg";
desc[2] = "http://www.kidsmathgamesonline.com/images/pictures/numbers600/number2.jpg";
desc[3] = "http://www.kidsmath`
Call here
function NextImage() {
imgNumber++;
if (imgNumber == NumberOfImages) {
imgNumber = 0;
}
document.images["largeImage"].src = img[imgNumber];
var desc = desc[imgNumber];
$('#description').text(desc);
}
function PreviousImage() {
imgNumber--;
if (imgNumber < 0) {
imgNumber = NumberOfImages - 1;
}
document.images["largeImage"].src = img[imgNumber];
var desc = desc[imgNumber];
$('#description').text(desc);
}
http://jsfiddle.net/rgvqA/2/
you just forgot to update your $('#description') element in next and prev functions

Javascript Click Function Broken in Gallery Script

I'm trying to create a gallery script with JS (I've only been learning for a week so please excuse if I've made any ridiculous mistakes!). When I run the code, I get an error for controlLeft.onclick = changeImage(--);, saying ( is an unexpected token.
By my untrained eye everything should be fine, but evidently not. What have I done wrong here:
//Javascript Image Changer
var currentImage = document.getElementById("currentImage");
var imageArray = ["img/1.jpg", "img/2.jpg", "img/3.jpg", "img/4.jpg"];
var imageIndex= 0;
function changeImage(param){
currentImage.setAttribute("src", imageArray[imageIndex]);
imageIndex[param];
if (imageIndex >= imageArray.length){
imageIndex = 0;
}else if(imageIndex <= -1){
imageIndex = imageArray.length + 1;
}
}
var controlLeft = document.getElementById("left");
var controlRight = document.getElementById("right");
controlLeft.onclick = changeImage(--);
controlRight.onclick = changeImage(++);
You can't just pass operators around like other things. Even in a programming language with higher-order functions the same thing usually does not apply to operators.
Besides that, onclick expects a function - not the result of a function call.
Here's a snippet that is likely to work:
function changeImage(mod){
currentImage.setAttribute("src", imageArray[imageIndex]);
imageIndex += mod;
if (imageIndex >= imageArray.length){
imageIndex = 0;
}else if(imageIndex <= -1){
imageIndex = imageArray.length + 1;
}
}
var controlLeft = document.getElementById("left");
var controlRight = document.getElementById("right");
controlLeft.onclick = function() { changeImage(-1); };
controlRight.onclick function() { changeImage(1); };
Just make a slight modification:
controlLeft.onclick = function() {
changeImage('back');
};
controlRight.onclick = function() {
changeImage('forward');
};

Javascript: get an image width and than set a class

I want to analyse every image of an article and set an class for all images smaller/equal than perhaps 400px (and another class for images bigger than 400px) so that I can give them a specific style.
In jQuery it would be perhaps something like this
$('div#content').find('img').each(function () {
var $this = $(this), width = $this.width();
if (width <= 400) {
$this.addClass('small_img');
}
var $this = $(this), width = $this.width();
if (width > 400) {
$this.addClass('large_img');
}
});
But I need it to be in pure Javascript. As a stupid Journalist and Webdesigner I don't get it... If you could help me, I would be very thankful.
You mean something FAST and short like this?
window.onload = function() {
var n=document.getElementById('content').getElementsByTagName('img'),
i=n.length;
while(i--){
n[i].className = n[i].clientWidth > 400 ? 'large_img' : 'small_img' ;
}
};
See this fiddle for working example.
Also read this question on SO for selecting a method to fetch the (computed) width.
window.onload = function() {
var content = document.getElementById('content');
if (content) {
var img = content.getElementsByTagName('img');
for (var i = 0, count = img.length; i < count; i++) {
if (img[i].offsetWidth <= 400) {
img[i].className += ' small_img';
} else {
img[i].className += ' large_img';
}
}
}
};
Something like this should work:
// Find the parent container 'div#content'
var container = document.getElementById( "content" ),
// Find all images within the parent
images = container.getElementsByTagName( "img" ),
// Total number of images to check
len = images.length,
// Loop counter
i = 0,
// Represents the current image in the loop
image;
// Loop through all the images
for ( ; i < len; i++ ) {
// Access the current image
image = images[ i ];
// Use the ternary operator to assign one of two classes, based on width
image.className += ( image.clientWidth > 400 ) ? " large_img" : " small_img";
}
Hope that helps. Cheers!
var contentDiv = document.getElementById('content');
var imgs = contentDiv.getElementsByTagName('img');
for(i=0;i<img.length;i++){
var img = imgs[i];
if(img.clientWidth <= 400) img.className += " small_img"
else img.className += " large_img"
}

Categories