Javascript image cycler - javascript

After the timer the image div goes blank instead of switching to the next picture. It is supposed to cycle images 1-4 and repeat indefinitely
$('.carouselImageJavascriptActive').removeClass('carouselImageJavascriptActive');
$(this).addClass('carouselImageJavascriptActive');
var imgs=$(this).attr('.carouselImage')
var self = $(this);
var myImage = new Array();
var x=0;
myImage[0]='img/image1.jpg';
myImage[1]='img/image2.jpg';
myImage[2]='img/image3.jpg';
myImage[3]='img/image4.jpg';
setTimeout(function() {
var img = document.getElementById('.carouselImageJavascriptActive');
img.src = myImage[x];
x++;
if(x >= myImage.length){
x = 0;
}
},2000);
HTML
<div id='challengeTwoImageJavascript' class='sectionChallengeCarouselImage'>
<img id='imgj1' imgn='1' class='carouselImage carouselImageJavascriptActive' src='img/image1.jpg'/>
<img id='imgj2' imgn='2' class='carouselImage' src='img/image2.jpg'/>
<img id='imgj3' imgn='3' class='carouselImage' src='img/image3.jpg'/>
<img id='imgj4' imgn='4'class='carouselImage' src='img/image4.jpg'/>
</div>

None of those images have an id of '.carouselImageJavascriptActive'.

Related

Traffic light on a timer using Javascript

I have been asked to create a traffic light that goes through the sequence set using arrays.
I have managed to create a traffic light that works with the user pressing a button every time they would like to change the colour of the traffic light however, I have now been tasked with making it so the user only has to press the button once and then it goes through the sequence automatically using JavaScript.
The images used in the code are located in the same folder as the script.
<img id="Change Lights" src="red.gif" width="36" height="98">
<br>
<button onclick="nxt()" id="button">Change colour</button>
</br>
<script>
var img = new Array("red.png", "amberred.png", "green.png", "amber.png");
var imgElement = document.getElementById("Change Lights");
var lights = 0;
var imgLen = img.length;
function nxt() {
if (lights < imgLen - 1) {
lights++;
} else {
lights = 0;
}
imgElement.src = img[lights];
}
</script>
<img id="Change Lights" src="https://placehold.it/36x98/ff0000" width="36" height="98">
<script>
var img = ["https://placehold.it/36x98/ffbf00","https://placehold.it/36x98/00ff00","https://placehold.it/36x98/ff0000"];
var imgElement = document.getElementById("Change Lights");
var lights = 0;
var imgLen = img.length;
function nxt() {
if (lights < imgLen - 1) {
lights++;
} else {
lights = 0;
}
imgElement.src = img[lights];
}
setInterval(nxt,2000);
</script>

JS onclick Event Handler - Not Responding

What I'm trying to achieve: clicking on any image should either reveal a clear image if image is blurred or blur the image if image is clear
What's happening: clicking on blurred image clears the image, but clicking on it again does nothing. so, clicking on a clear image does not blur it (as it should).
Here's my code:
<script>
window.onload = init;
function init(e) {
var img = document.getElementsByTagName("img");
//var img = document.getElementById('pics');
img[0].onclick = unblur; // <- why not just img.onclick = unblur ??
img[1].onclick = unblur;
img[2].onclick = unblur;
console.log(img);
/*
var imageId = e.target.id; //zero
var img = document.getElementById(imageId);
*/
//img.onclick = unblur;
}
function unblur(e) {
var imageId = e.target.id; //zero
var img = document.getElementById(imageId);
var imageSource = img.src; //zeroblur.jpg
var clearImg = imageSource.substring(0, imageSource.length - 8);
var unblurredImg = imageId.concat('.jpg'); // zero.jpg
var blurredImg = imageId.concat('blur.jpg'); // zeroblur.jpg
console.log(imageSource);
console.log(img.src);
//console.log(imageSource);
if (img.src == unblurredImg) {
img.src = blurredImg;
} else {
img.src = unblurredImg; // image is clear, so hide the pic
}
/*
if (img.src == blurredImg) {
img.src = unblurredImg;
}
} */
//}
}
/*
//if (!(imageId instanceof img)) {
if (imageId !== "pics") {
if (img.src == blurredImg) {
img.src = unblurredImg;
} else if (img.src == unblurredImg) {
img.src = blurredImg;
} // image is blurred, so reveal the pic
else {
console.log("hi");
}
//debugger;
}
}
*/
/*
var img = document.getElementById('zero');
img.src = "zero.jpg";
*/
</script>
</head>
<body>
<div id="pics">
<img id="zero" src="zeroblur.jpg">
<img id="one" src="oneblur.jpg">
<img id="two" src="two.jpg">
</div>
</body>
</html>
I also noticed that if I switch the conditions in the function, unblur(e), to the following...
if (img.src == unblurredImg) {
img.src = blurredImg;
} else {
img.src = unblurredImg;
}
there's no response at all if a user clicks on a blurred image, whereas before (code above) the blurred image will at least reveal the cleared image.
Why is this happening? I see no difference between the two, besides just switching the order of the conditions.
There are various mistakes in your example. Take a look at the Code Snippet for a working example of what you are trying to achieve.
As for your comment:
// <- why not just img.onclick = unblur ??
Because document.getElementsByTagName returns an array of elements. Therefore, you must iterate through the elements to apply the onclick handlers to each one.
(function(document) {
var array = document.getElementsByTagName("img");
for (var i = 0; i < array.length; i++) {
array[i].onclick = toggleBlur;
}
function toggleBlur(event) {
var img = event.target;
var oldSrc = img.src; // Save to display in the console
if (img.src.endsWith("blur.jpg")) {
img.src = img.id + ".jpg";
} else {
img.src = img.id + "blur.jpg"
}
console.log(oldSrc + " -> " + img.src + " on element.id=" + img.id);
}
})(document);
<body>
<div id="pics">
<img id="zero" src="zero.jpg">
<img id="one" src="one.jpg">
<img id="two" src="twoblur.jpg">
</div>
</body>

html image sldeshow not changing images

ive scripted my self a Image slideshowthere is just the issue that the slideshow stays static on the first Image for each Group.
this Code here is where i have all my Images and then they get selected from it.
< script type = "text/javascript" >
<!-->
var image1 = new Image()
image1.src = "LMH2015_SGVillingen_P1220967.jpg"
var image2 = new Image()
image2.src = "LMH2015_SGVillingen_P1220971.jpg"
var image3 = new Image()
image3.src = "LMH2015_SGVillingen_P1220973.jpg"
var image4 = new Image()
image4.src = "LMH2015_SGVillingen_P1220977.jpg"
var image5 = new Image()
image5.src = "LMH2015_SGVillingen_P1220985.jpg"
//-->
< /script>
and the second part is where the JavaScript should creat the slideshow.
<img src="LMH2015_SGVillingen_P1220967.jpg" width="300" height="300" name="slide" />
<script type="text/javascript">
var step=1
function slideit()
{
document.images.slide.src = eval("image"+step+".src")
if(step<3)
step++
else
step=1
setTimeout("slideit()",3000)
}
slideit()
</script>
<img src="LMH2015_SGVillingen_P1220977.jpg" width="300" height="300" name="slide" />
<script type="text/javascript">
var step=4
function slideit()
{
document.images.slide.src = eval("image"+step+".src")
if(step<5)
step++
else
step=4
setTimeout("slideit()",3000)
}
slideit()
</script>
I hope that there is an easy way of Fixing this Problem and that the way i was having it with the Images still could be left to make it a bit easier is view the Code :D
mark
Try the below function and it is dynamic just call the function with array image and duration.
HTML
<img src="" width="300" height="300" name="slide" />
JS
var imageArr = ["http://stylonica.com/wp-content/uploads/2014/02/Beauty-of-nature-random-4884759-1280-800.jpg", "http://stylonica.com/wp-content/uploads/2014/02/Free-Wallpaper-Nature-Scenes.jpg", "http://www.viralnovelty.net/wp-content/uploads/2014/07/121.jpg"];
function slideShow(imageName, imgArray, duration) {//pass image array and time duration
if(imgArray.constructor !== Array) {
alert("proovide valid image array for slide show");
return false;
}
var step=0;
setInterval(function(){
if(step > imgArray.length - 1){
step = 0; //reset count when the last image
}
document.images[imageName].src = imgArray[step];
step++;
}, duration);
}
slideshow('slide', imageArr, 5000);//call the function with image name
demo link: Slideshow

Random image appear when website is loaded

I have 2 pictures for my website, and i want it to load one of them whem the website loads.
I have tried using some javascript. But i am quite new to all this.
This is how i am think i want to make it.
<div class="image">
Show one of 2 images here.
</div>
<script>
var r = Math.floor(Math.random() * 100) + 1;
if(r < 51) {
SHOW IMAGE 1
}
else {
SHOWIMAGE 2
}
</sccript>
So i was hoping someone could teach me how to actually turn this into functional code.
Thanks.
You can set the src attribute of an image directly using javascript, then use Math.random like you expected to pick between different image urls.
With an image tag with id 'random_image':
// images from wikipedia featured images/articles 2015-03-03
var img = document.getElementById('random_image');
if (Math.random() > .5) {
img.src = 'http://upload.wikimedia.org/wikipedia/en/thumb/4/45/Bradford1911.jpg/266px-Bradford1911.jpg';
} else {
img.src = 'http://upload.wikimedia.org/wikipedia/commons/thumb/a/ae/Pitta_sordida_-_Sri_Phang_Nga.jpg/720px-Pitta_sordida_-_Sri_Phang_Nga.jpg';
}
Here is a jsfiddle example: http://jsfiddle.net/8zd5509u/
1.way:
var _img = document.getElementById('id1');
var newImg = new Image;
newImg.onload = function() {
_img.src = this.src;
}
newImg.src = 'http://www.something.blabla.....';
another:
function preload(images) {
if (document.images) {
var i = 0;
var imageArray = new Array();
imageArray = images.split(',');
var imageObj = new Image();
for(i=0; i<=imageArray.length-1; i++) {
//document.write('<img src="' + imageArray[i] + '" />');// Write to page (uncomment to check images)
imageObj.src=imageArray[i];
}
}
}
Then in the of each web page, add the following code after you've called the main JavaScript file:
<script type="text/javascript">
preload('image1.jpg,image2.jpg,image3.jpg');
</script>

Preloader for loading images

I am currently working on SVG SMIL animation in which I am using some .png and .gif files for easing my animation in IE. For this animation I am trying to get Preloader before animation and its other contents get loaded.
Problem is I am not getting that Preloader working properly. My .html page is getting loaded first and then preloader is starting... In Preloader also, I have used several preloaders available on the web. But they are not helpful for me.
Script and .html files loading time can be counted by domContentLoaded but for images. I dont know how to do that. If someone can suggest me a way that would be great.
here is code of preloader.js, I found on web:
$(document).ready(function () {
"use strict"
//indexOf support for IE8 and below.
if (!Array.prototype.indexOf){
Array.prototype.indexOf = function(elt /*, from*/){
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++){
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
//bgImg for holding background images in the page & img array for images present in the document(<img src="">).
var bgImg = [], img = [], count=0, percentage = 0;
//Creating loader holder.
$('<div id="loaderMask"><span>0%</span></div>').css({
position:"fixed",
top:0,
bottom:0,
left:0,
right:0,
background:'#fff'
}).appendTo('body');
//Using jQuery filter method we parse all elemnts in the page and adds background image url & images src into respective arrays.
$('*').filter(function() {
var val = $(this).css('background-image').replace(/url\(/g,'').replace(/\)/,'').replace(/"/g,'');
var imgVal = $(this).not('image').attr('xlink:href');
//Getting urls of background images.
if(val !== 'none' && !/linear-gradient/g.test(val) && bgImg.indexOf(val) === -1){
bgImg.push(val)
}
//Getting src of images in the document.
if(imgVal !== undefined && img.indexOf(imgVal) === -1){
img.push(imgVal)
}
});
//Merging both bg image array & img src array
var imgArray = bgImg.concat(img);
console.log(imgArray.length);
//Adding events for all the images in the array.
$.each(imgArray, function(i,val){
//Attaching load event
$("<image />").attr("xlink:href", val).bind("load", function () {
console.log('val'+val);
completeImageLoading();
});
//Attaching error event
$("<image />").attr("xlink:href", val).bind("error", function () {
imgError(this);
});
})
//After each successful image load we will create percentage.
function completeImageLoading(){
count++;
percentage = Math.floor(count / imgArray.length * 100);
console.log('percentage:'+percentage);
$('#loaderMask').html('<span>'+percentage + '%'+'</span>');
//When percentage is 100 we will remove loader and display page.
if(percentage == 100){
$('#loaderMask').html('<span>100%</span>')
$('#loaderMask').fadeOut(function(){
$('#loaderMask').remove()
})
}
}
//Error handling - When image fails to load we will remove the mask & shows the page.
function imgError (arg) {
$('#loaderMask').html("Image failed to load.. Loader quitting..").delay(3000).fadeOut(1000, function(){
$('#loaderMask').remove();
})
}
});
A little trick I do to ensure my or external data or images are loaded before I start executing my js code is, I create a div with display:none and fill it with all the tags that I need loaded.
<body>
<span id="loadingText">Loading...</span>
<div style="display:none">
<img src="pathtoimage1">
<img src="pathtoimage2">
<img src="pathtoimage3">
</div>
<script>
window.onload = function(){
//This gets called when all the items in that div has been loaded and cached.
document.getElementById("loadingText").style.display = "none";
}
</script>
</body>
I use this for preloading images for animations.
you can add and remove how many you load as needed.
<script language="javascript">function preloader() {
if (document.images) {
var img1 = new Image();
var img2 = new Image();
var img3 = new Image();
var img4 = new Image();
var img5 = new Image();
var img6 = new Image();
var img7 = new Image();
var img8 = new Image();
var img9 = new Image();
img1.src = "image link here";
img2.src = "image link here";
img3.src = "image link here";
img4.src = "image link here";
img5.src = "image link here";
img6.src = "image link here";
img7.src = "image link here";
img8.src = "image link here";
img9.src = "image link here";
}
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(preloader);</script>

Categories

Resources