adding current class to automated image changer - javascript

I have a kind of a image rotator that scrolls through an array of images via javascript within a certain interval, and now I have added some style to each current image. But that only works if I myself hover over the items/click on the items, whenever the script swaps images on auto, nothing happens stylistically to the images.
So what I want to know is how I can use the same effect on the auto script.
Here is the code
*HTML *
<div class="container-thumbs">
<div><a><img src=".jpg" /></a></div>
<div><a class="active"><img src=".jpg" /></a></div>
<div><a><img src=".jpg" /></a></div>
</div>
CSS
.container-thumbs{
width: 300px; height: 25; font-size: 18px;
}
.container-thumbs a{
list-style: none; float: left; margin-right: 4px; padding: 5px;
}
.container-thumbs div a:hover, .container-thumbs div a.active {
background-color: #f90;
}
Javascript
(function(){
var rotator = document.getElementById('bigImage');
var imageDir = '../images/headers/';
var delayInSeconds = 5;
var images = ['.jpg', '.jpg', '.jpg', '.jpg', '.jpg',
'.jpg', '.jpg'];
var num = 0;
var changeImage = function() {
var len = images.length;
bigImage.src = imageDir + images[num++];
if (num == len)
{num = 0;}
};
setInterval(changeImage, delayInSeconds * 1000);
})();

i think u have to replace bigImage with rotator
because the u getTheImage
var rotator = document.getElementById('bigImage');
// then u dont use it
bigImage.src = imageDir + images[num++];
// so try to change to
rotator.src=imageDir + images[num++];
goodluck

From your html there is no element with an ID of bigImage, so I cannot see how this works at all.
I have added the ID in the middle image as below:
<div class="container-thumbs">
<div><a><img src=".jpg" /></a></div>
<div><a class="active"><img src=".jpg" id="bigImage" /></a></div>
<div><a><img src=".jpg" /></a></div>
</div>
That should work.
One other thing, is there a good reason not to use jQuery here? I'd strongly recommend it for cross-browser compatibility if nothing else.

Related

How to change image by clicking on event?

I tried but it's not working. When I click on .imgChangeBtn element, this element’s src value will be puss on the #imgDisplay element.
Note imgPath variable is not getting any value. And Anonymous function is not set on this element. I don't know why!
<img id="imgDisplay" src="default.jpg"/>
<ul>
<li><img class="imgChangeBtn" src="wolverine.jpg"></li>
<li><img class="imgChangeBtn" src="Iron_man.jpg"></li>
</ul>
<script>
var DisplayBoard = document.querySelector("#imgDisplay");
var ChangeBtn = document.querySelector(".imgChangeBtn");
ChangeBtn.click(function () {
var imgPath = document.querySelector('.imgChangeBtn').getAttribute('src');
DisplayBoard.src = imgPath;
console.log(imgPath);
})
</script>
You should loop through all the elements with the class imgChangeBtn using querySelectorAll then attach the click listener using addEventListener in every iteration, check the snippet below.
Hope this helps.
var displayBoard = document.querySelector("#imgDisplay");
var changeBtnList = document.querySelectorAll(".imgChangeBtn");
for (var i = 0; i < changeBtnList.length; i++) {
changeBtnList[i].addEventListener('click', changeSrc);
}
function changeSrc() {
var imgPath = this.getAttribute('src');
displayBoard.src = imgPath;
console.log(displayBoard.src);
}
<img id="imgDisplay" src="default.jpg" />
<ul>
<li><img class="imgChangeBtn" src="wolverine.jpg" alt="wolverine.jpg" /></li>
<li><img class="imgChangeBtn" src="Iron_man.jpg" alt="Iron_man.jpg" /></li>
</ul>
Use document.querySelector('.imgChangeBtn').setAttribute("src", imgPath); in order to set src.
You need to do it like below. You can also reference 'this' within the function, to make your code shorter.
var DisplayBoard = document.querySelector("#imgDisplay");
var ChangeBtn = document.querySelector(".imgChangeBtn");
ChangeBtn.onclick = function () {
var imgPath = this.getAttribute('src');
DisplayBoard.src = imgPath;
console.log(imgPath);
};
I created you a codepen for what I think you are trying to achieve, requires jQuery: https://codepen.io/MayhemBliz/pen/eerzdJ
$("img").on("click", function() {
var selectedImgSrc = $(this).attr("src");
console.log(selectedImgSrc);
$("#img").attr("src",selectedImgSrc);
});
#img {
display: block;
object-fit: cover;
width: 200px;
height: 200px;
margin-bottom: 10px;
}
ul {
list-style: none;
padding: 0;
font-size: 0;
}
li {
display: inline-block;
}
img {
display: block;
width: 100px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="img" src="https://media.giphy.com/media/xnscj78AnbBm/giphy.gif"/>
<ul>
<li><img src="https://media.giphy.com/media/dWOhtHvkWgRq0/giphy.gif"></li>
<li><img src="https://media.giphy.com/media/xnscj78AnbBm/giphy.gif"></li>
</ul>

How can I add a link around every image on a page?

I want to add a link to all images on the page. The link should point to the image source.
For example, from this:
<img src="foo.jpg">
I want to get this:
<img src="foo.jpg">
I tried to do it like the following but nothing seems to happen. Do I then have to somehow add the new "a" element somewhere?
var images = document.getElementsByTagName('img');
for (var image in images) {
var a = document.createElement('a');
a.href = image.src;
a.innerHtml = image;
}
You are iterating over the indices (0, 1, 2, ...) of images in this line:
for (var image in images) {
If image were an HTML element, this line still wouldn't work because the innerHTML property expects HTML text, not an object:
a.innerHtml = image;
Finally, you have neglected to add the anchor to the document.
Here is a correct way to do it:
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; ++i) {
var img = images[i];
var a = document.createElement('a'); // Make a new anchor.
a.href = img.src; // Point it at the image source.
img.parentNode.replaceChild(a, img); // Replace the image with the anchor.
a.appendChild(img); // Make the image a child of the anchor.
}
<img src="http://i.stack.imgur.com/bcOyt.png">
<img src="http://i.stack.imgur.com/IPkNZ.png">
<img src="http://i.stack.imgur.com/Kd7GM.png">
You just create the Tag, but not insert it to the Document.
You can use replaceChild method in Node to replace the Img tag.
May I suggest jQuery?
The following example won't work in the sandbox because of browser restrictions, but should work on a site that you control. Also, depending on circumstances, the browser might block the popup. But, in the case of links within the webpage own domain, this might be the better solution, because you avoid manipulating the DOM.
$(function () {
$('img').on('click', function () {
var win = window.open($(this).attr('src'), '_blank')
win.focus()
})
})
img {
border: 1px solid blue;
cursor: pointer;
float: left;
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
Here is another approach, wrapping all the images in an a tag as you originally requested:
$(function () {
$('img').wrap(function () {
return ''
})
})
img {
border: 1px solid blue;
cursor: pointer;
float: left;
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
for each loops are somewhat strange in javascript, you need to access objects like this:
for (var image in images) {
var a = document.createElement('a');
a.href = images[image].src;
a.innerHtml = images[image];
a.appendChild(images[image]);
// then of course you need to replace the img with the anchor containing the image
images[image].parentNode.replaceChild(a, images[image]);
}
Generally speaking:
for(var obj in list) {
var current = list[obj];
}

How can I change the x position of a div via javascript when I click on another div this way?

<body>
<div id = "SiteContainer">
<div id = "NavigationButtons"></div>
<div id = "ShowReelContainer">
<div id= "NavigationBackward" name = "back" onclick="setPosition();">x</div>
<div id= "NavigationForward" name = "forward" onclick="setPosition();">y</div>
<div id = "VideoWrapper">
<div id = "SlideShowItem">
<img src="Images/A.png" alt="A"></img>
</div>
<div id = "SlideShowItem">
<img src="Images/B.png" alt="B"></img>
</div>
<div id = "SlideShowItem">
<img src="Images/C.png" alt="C" ></img>
</div>
</div>
</div>
</div>
<script>
var wrapper = document.querySelector("#VideoWrapper");
function setPosition(e)
{
if(e.target.name = "forward")
{
if!(wrapper.style.left = "-200%")
{
wrapper.style.left = wrapper.style.left - 100%;
}
}
else
{
if(e.target.name = "back")
{
if!(wrapper.style.left = "0%")
{
wrapper.style.left = wrapper.style.left + 100%;
}
}
}
}
</script>
</body>
Hi, I am very new to javascript. What I am trying to do, is change the x-position of a div when another div (NavigationForward or NavigationBackward) is clicked. However it does not appear to do anything at all. Basically if the div with name forward is clicked, I want to translate the VideoWrapper -100% from it's current position and +100% when "back". The css div itself VideoWrapper has a width of 300%. Inside this div as you can see is a SlideShowItem which is what will change. Perhaps I am adding and subtracting 100% the wrong way?
EDIT:
Thanks everyone for helping me out with this...I had just one more query, I am trying to hide the arrows based on whether the wrapper is at the first slide or the last slide. If its on the first slide, then I'd hide the left arrow div and if it's on the last, I'd hide the right arrow, otherwise display both of em. Ive tried several ways to achieve this, but none of em work, so Ive resorted to using copies of variables from the function that works. Even then it does not work. It appears that my if and else if statements always evaluate to false, so perhaps I am not retrieving the position properly?
function HideArrows()
{
var wrapper2 = document.getElementById("VideoWrapper");
var offset_x2 = wrapper2.style.left;
if(parseInt(offset_x2,10) == max_x)
{
document.getElementById("NavigationForward").display = 'none';
}
else if(parseInt(offset_x2,10) == min_x)
{
document.getElementById("NavigationBackward").display = 'none';
}
else
{
document.getElementById("NavigationForward").display = 'inline-block';
document.getElementById("NavigationBackward").display = 'inline-block';
}
}
//html is the same except that I added a mouseover = "HideArrows();"
<div id = "ShowReelContainer" onmouseover="HideArrows();">
To achieve this type o slider functionality your div VideoWrapper must have overflow:hidden style, and your SlideShowItemdivs must have a position:relative style.
Then to move the slides forward or backward you can use the style left which allows you to move the divs SlideShowItem relative to it's parent VideoWrapper.
I've tested this here on JSFiddle.
It seems to work as you described in your question, although you may need to do some adjustments, like defining the width of your slides, how many they are and so on.
For the sake of simplicity, I defined them as "constants" on the top of the code, but I think you can work from that point on.
CSS
#VideoWrapper{
position:relative; height:100px; white-space:nowrap;width:500px;
margin-left:0px; border:1px solid #000; overflow:hidden; }
.SlideShowItem{
width:500px; height:100px;display:inline-block;position:relative; }
#NavigationForward, #NavigationBackward{
cursor:pointer;float:left; background-color:silver;margin-right:5px;
margin-bottom:10px; text-align:center; padding:10px; }
HTML
<div id = "SiteContainer">
<div id = "NavigationButtons">
</div>
<div id = "ShowReelContainer">
<div id= "NavigationBackward" name = "back" onclick="setPosition('back');">prev</div>
<div id= "NavigationForward" name = "forward" onclick="setPosition('forward');">next</div>
<div style="clear:both;"></div>
<div id = "VideoWrapper">
<div class= "SlideShowItem" style="background-color:blue;">
Slide 1
</div>
<div class = "SlideShowItem" style="background-color:yellow;">
Slide 2
</div>
<div class = "SlideShowItem" style="background-color:pink;">
Slide 3
</div>
</div>
</div>
</div>
JavaScript
var unit = 'px'; var margin = 4; var itemSize = 500 + margin; var itemCount = 3; var min_x = 0; var max_x = -(itemCount-1) * itemSize;
function setPosition(e) {
var wrapper = document.getElementById("VideoWrapper");
var slides = wrapper.getElementsByTagName('div');
var offset_x = slides[0].style.left.replace(unit, '');
var curr_x = parseInt(offset_x.length == 0 ? 0 : offset_x);
if(e == "forward")
{
if(curr_x <= max_x)
return;
for(var i=0; i<slides.length; i++)
slides[i].style.left= (curr_x + -itemSize) + unit;
}
else if(e == "back")
{
if(curr_x >= min_x)
return;
for(var i=0; i<slides.length; i++)
slides[i].style.left= (curr_x + itemSize) + unit;
} }
After you analyze and test the code, I don't really know what's your purpose with this, I mean, you maybe just playing around or trying to develop something for a personal project, but if you are looking for something more professional avoid to create things like sliders on your own, as there are tons of plugins like this available and well tested out there on the web.
Consider using jQuery with NivoSlider, it works like a charm and is cross browser.
I would recommend using jQuery, this will reduce your coding by quite a bit. Can read more here: http://api.jquery.com/animate/
I've created a simple fiddle for you to take a look at. This example uses the .animate() method to reposition two div elements based on the CSS 'left' property.
CSS:
#container {
position: absolute;
left: 1em;
top: 1em;
right: 1em;
bottom: 1em;
overflow: hidden;
}
#one, #two {
position: absolute;
color: white;
}
#one {
background: pink;
width: 100%;
top:0;
bottom:0;
}
#two {
background: blue;
width: 100%;
left: 100%;
top:0;
bottom:0;
}
HTML:
<div id="container">
<div id="one">Div One</div>
<div id="two">Div Two</div>
</div>
JavaScript/jQuery:
var one, two, container;
function animateSlides(){
one.animate({
left : '-100%'
}, 1000, function(){
one.animate({
left : 0
}, 1000);
});
two.animate({
left : 0
}, 1000, function(){
two.animate({
left:'100%'
}, 1000);
});
};
$(function(){
one = $('#one');
two = $('#two');
container = $('#container');
setInterval(animateSlides, 2000);
});
JSFiddle Example: http://jsfiddle.net/adamfullen/vSSK8/3/

Show images one after one after some interval of time

I am new person in Front End Development and i am facing one major problem is that i have 3 images placed on each others and now i want to move one image so the other image comes up and then it goes and third image comes up after some interval of time.
I want three images on same position in my site but only wants to see these three images one after one after some interval of time.
Please help how i can do this??
May i use marquee property or javascript???
Non-jQuery Option
If you don't want to go down the jquery route, you can try http://www.menucool.com/javascript-image-slider. The setup is just as easy, you just have to make sure that your images are in a div with id of slider and that div has the same dimensions as one of your images.
jQuery Option
The jQuery cycle plugin will help you achieve this. It requires jquery to work but it doesn't need much setting up to create a simple sliple slideshow.
Have a look at the 'super basic' demo:
$(document).ready(function() {
$('.slideshow').cycle({
fx: 'fade' // choose your transition type, ex: fade, scrollUp, shuffle, etc...
});
});
It has many options if you want something a bit fancier.
Here you go PURE JavaScript solution:
EDIT I have added image rotation... Check out live example (link below)
<script>
var current = 0;
var rotator_obj = null;
var images_array = new Array();
images_array[0] = "rotator_1";
images_array[1] = "rotator_2";
images_array[2] = "rotator_3";
var rotate_them = setInterval(function(){rotating()},4000);
function rotating(){
rotator_obj = document.getElementById(images_array[current]);
if(current != 0) {
var rotator_obj_pass = document.getElementById(images_array[current-1]);
rotator_obj_pass.style.left = "-320px";
}
else {
rotator_obj.style.left = "-320px";
}
var slideit = setInterval(function(){change_position(rotator_obj)},30);
current++;
if (current == images_array.length+1) {
var rotator_obj_passed = document.getElementById(images_array[current-2]);
rotator_obj_passed.style.left = "-320px";
current = 0;
rotating();
}
}
function change_position(rotator_obj, type) {
var intleft = parseInt(rotator_obj.style.left);
if (intleft != 0) {
rotator_obj.style.left = intleft + 32 + "px";
}
else if (intleft == 0) {
clearInterval(slideit);
}
}
</script>
<style>
#rotate_outer {
position: absolute;
top: 50%;
left: 50%;
width: 320px;
height: 240px;
margin-top: -120px;
margin-left: -160px;
overflow: hidden;
}
#rotate_outer img {
position: absolute;
top: 0px;
left: 0px;
}
</style>
<html>
<head>
</head>
<body onload="rotating();">
<div id="rotate_outer">
<img src="0.jpg" id="rotator_1" style="left: -320px;" />
<img src="1.jpg" id="rotator_2" style="left: -320px;" />
<img src="2.jpg" id="rotator_3" style="left: -320px;" />
</div>
</body>
</html>
And a working example:
http://simplestudio.rs/yard/rotate/rotate.html
If you aim for good transition and effect, I suggest an image slider called "jqFancyTransitions"
<html>
<head>
<script type="text/javascript">
window.onload = function(){
window.displayImgCount = 0;
function cycleImage(){
if (displayImgCount !== 0) {
document.getElementById("img" + displayImgCount).style.display = "none";
}
displayImgCount = displayImgCount === 3 ? 1 : displayImgCount + 1;
document.getElementById("img" + displayImgCount).style.display = "block";
setTimeout(cycleImage, 1000);
}
cycleImage();
}
</script>
</head>
<body>
<img id="img1" src="./img1.png" style="display: none">
<img id="img2" src="./img2.png" style="display: none">
<img id="img3" src="./img3.png" style="display: none">
</body>
</html>​
Fiddle: http://jsfiddle.net/SReject/F7haV/
arrayImageSource= ["Image1","Image2","Image3"];
setInterval(cycle, 2000);
var count = 0;
function cycle()
{
image.src = arrayImageSource[count]
count = (count === 2) ? 0 : count + 1;
}​
Maybe something like this?

Javascript slideshow cycles fine twice, then bugs out

I followed a tutorial to create a simple javascript slideshow but I am having a strange bug... The first 2 cycles work perfectly, but once the counter resets the slideshow begins showing the previous slide quickly then trying to fade in the correct slide. Any idea what is causing this?
I have 3 images (named Image1.png, Image2.png, and Image3.png) in a folder for my simple slideshow and 3 divs set up like this:
<div id="SlideshowFeature">
<div id="counter">
3
</div>
<div class="behind">
<img src="SlideShow/image1.png" alt="IMAGE" />
</div>
<div class="infront">
<img src="SlideShow/image1.png" alt="IMAGE" />
</div>
</div>
My javascript looks like this
var nextImage;
var imagesInShow;
var currentImage;
var currentSrc
var nextSrc
function changeImage() {
imagesInShow = "3";
currentImage = $("#counter").html();
currentImage = parseInt(currentImage);
if (currentImage == imagesInShow) {
nextImage = 1;
}
else {
nextImage = currentImage + 1;
}
currentSrc = $(".infront img").attr("src");
nextSrc = "SlideShow/image" + nextImage + ".png";
$(".behind img").attr("src", currentSrc);
$(".infront").css("display", "none");
$(".infront img").attr("src", nextSrc);
$(".infront").fadeIn(1000);
$("#counter").html(nextImage);
setTimeout('changeImage()', 5000);
}
$(document).ready(function () {
changeImage();
});
EDIT:
Also here is my CSS
#SlideshowFeature
{
text-align:center;
margin: 0 auto;
width:800px;
background: #02183B;
height:300px;
float: left;
overflow:hidden;
display:inline;
}
#SlideshowFeature div
{
width: 800px;
height:300px;
position:absolute;
}
#counter
{
display:none;
}
The problem seem to be in your HTML structure (and not in your JS):
...
<img src="SlideShow/image1.png" alt="IMAGE" />
...
<img src="SlideShow/image1.png" alt="IMAGE" />
...
I think you meant to put image1.png and then image2.png
.infront must be in front and .behind must be behind
.behind {
z-index: 1;
}
.infront {
z-index: 255;
}
And I also moved re-scheduling logic to fadeIn callback:
$(".infront").fadeIn(1000, function(){setTimeout('changeImage()', 2500)});
$("#counter").html(nextImage);
//setTimeout('changeImage()', 2500);
Looks good for me now.

Categories

Resources