How to change image by clicking on event? - javascript

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>

Related

How to shade an image and keep the value assigned in it in javascript?

I would like to know how I can click on an image like this
If I click on the BMW or Toyota logo then it shades the icon I have selected with CSS then keep that 'value' and save it in javascript variable so I can use later.
Let's say I have this
<ul class="car_types">
<li class="bmw"><img src="test/bmw.png"></li>
<li class="audi"><img src="test/audi.png"></li>
<li class="toyota"><img src="test/toyota.jpg"></li>
<li class="benz"><img src="test/benz.jpg">Discover</li>
</ul>
or i have
<table>
<tr>
<div class="car_types">
<img id="bmw" src="test/bmw.png">
<img id="audi" src="test/audi.png">
<img id="toyota" src="test/toyota.jpg">
<img id="benz" src="test/benz.jpg">
</div>
</tr>
</table>
or any other way of doing it.
Many thanks.
You need to add an event listener to each of your images, so that you can select which image should be highlighted.
Then, create a special css class which gives a special style to the selected image.
I've created a simple demo below:
Here, we have a listener that listens on the "click" event on the <li> elements inside of your .car_types list. When we do click on an image, we remove any elements that might have the shaded class (from a previous click), and then add the shaded class to the one we just clicked on.
The shaded class just gives a 50% brightness, instead of 100%.
$(".car_types li").on("click", function(){
$(".car_types li").each(function() {
$(this).removeClass("shaded");
});
$(this).addClass("shaded");
});
.car_types li {
display: inline-block;
}
.shaded {
filter: brightness(50%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="car_types">
<li class="bmw"><img src="http://via.placeholder.com/135x135"></li>
<li class="audi shaded"><img src="http://via.placeholder.com/135x135"></li>
<li class="toyota"><img src="http://via.placeholder.com/135x135"></li>
<li class="benz"><img src="http://via.placeholder.com/135x135"></li>
</ul>
If you want to be able to shade several logos at once, try this instead:
$(".car_types li").on("click", function(){
if($(this).hasClass("shaded")) {
$(this).removeClass("shaded");
} else {
$(this).addClass("shaded");
}
});
.car_types li {
display: inline-block;
}
.shaded {
filter: brightness(50%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="car_types">
<li class="bmw"><img src="http://via.placeholder.com/135x135"></li>
<li class="audi shaded"><img src="http://via.placeholder.com/135x135"></li>
<li class="toyota"><img src="http://via.placeholder.com/135x135"></li>
<li class="benz"><img src="http://via.placeholder.com/135x135"></li>
</ul>
Here it is with pure JS
HTMLCollection.prototype.each = function(cb) { for(var i = 0; i < this.length; i++) {
cb(this[i], i);
}
}
var imgs = document.getElementsByTagName('img');
imgs.each(function(img) {
img.addEventListener('click', function(ev) {
imgs.each(function(img) {
img.classList.remove('selected');
});
ev.target.classList.add('selected');
});
});
img {
opacity: .8;
}
.selected {
opacity: 1;
}
<ul class="car_types">
<li class="bmw"><img src="test/bmw.png"></li>
<li class="audi"><img src="test/audi.png"></li>
<li class="toyota"><img src="test/toyota.jpg"></li>
<li class="benz"><img src="test/benz.jpg">Discover</li>
</ul>
Considering you have added event listener like this,
Have a global variable in your js file and modify it on click event..
var selectedVal; //global variable for value
$(".car_types li").on("click", function(){
$(".car_types li").each(function() {
$(this).removeClass("shaded");
});
$(this).addClass("shaded");
selectedVal=$(this).data("val"); //modifying global variable
});
//access selectedVal anywhere
HTML:
<ul class="car_types">
<li class="bmw" data-val="bmw"><img src="test/bmw.png"></li>
<li class="audi" data-val="audi"><img src="test/audi.png"></li>
<li class="toyota" data-val="toyota"><img src="test/toyota.jpg"></li>
<li class="benz" data-val="benz"><img src="test/benz.jpg">Discover</li>
</ul>
CSS:
.shaded{
box-shadow:0px 0px 20px black;
}
Usually, you add a click listener to the image. This click listener then adds a selected class to the image. The image has styles which it applies when there is a .selected class on the image. These styles should then shade the image. The click listener also sets the JavaScript variable which you can then use.
Here is an example with plain JavaScript (no jQuery):
var selectedCar = 'no car selected';
var allCarTypes = document.querySelectorAll('.car_type');
allCarTypes.forEach(function (item) {
item.addEventListener('click', function (event) {
var selectedElement = event.target;
removeSelectedClassForAllElements();
selectedElement.classList.add('selected');
selectedCar = selectedElement.id;
});
});
function removeSelectedClassForAllElements () {
allCarTypes.forEach(function (item) {
item.classList.remove('selected');
});
}
.car_type {
width: 130px;
height: 130px;
position: relative;
cursor: pointer;
}
.car_type:after {
content: "";
position: absolute;
top: 0;
left: 0;
display: block;
height: 100%;
width: 100%;
background: rgba(0, 0, 0, 0.5);
transition: 0.3s ease all;
opacity: 0;
visibility: hidden;
}
.car_type.selected:after {
opacity: 1;
visibility: visible
}
<div class="car_types">
<img id="bmw" class="car_type" src="test/bmw.png">
<img id="audi" class="car_type" src="test/audi.png">
<img id="toyota" class="car_type" src="test/toyota.jpg">
<img id="benz" class="car_type" src="test/benz.jpg">
</div>
<!-- do not use 'onclick' -->
<button onclick="alert(selectedCar);">Which car is selected?</button>

I want to create image slider by using mouse drag without using extra plugins

I want to create image slider by using mouse drag without using extra plugins. Is there any mathematical formula to be used in jQuery to get this with help of following functions?
$(".cont").on("mousestart",function() {
$(".cont").on("mouseend",function() {
});
});
I don't want external plugins
here is the example of changing image on click event. you can also bind any other event if require.
$(function () {
var transition_speed = 300;
var simple_slideshow = $("#exampleSlider"),
listItems = simple_slideshow.children('li'),
listLen = listItems.length,i = 0;
changeList = function () {
listItems.eq(i)
.fadeOut(transition_speed,function () {
i += 1;
if (i === listLen) {
i = 0;
}
listItems.eq(i).fadeIn(transition_speed);
});
};
listItems.not(':first').hide();
$('#exampleSlider').on('click', function () {
changeList(); // Do this once immediately
})
});
img {
width: 100%:
}
#exampleSlider {
max-height: 250px;
overflow: hidden;
list-style: none;
padding: 0;
width:500px;
margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="exampleSlider">
<li><img src="http://placehold.it/500x250" alt="" /></li>
<li><img src="http://placehold.it/500x260" alt="" /></li>
<li><img src="http://placehold.it/500x270" alt="" /></li>
<li><img src="http://placehold.it/500x280" alt="" /></li>
</ul>

How to change code so that pictures be in "main-block", instead of a js-code? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
How to change this javascript code - http://jsbin.com/ciduhegukinu/2/edit
How to change this code so that pictures be in "main-block", instead of a js-code. And then already to bring them in the slides array in javascript.
And that the structure of all the page was following:
I want:
------------------------
Big picture (100% width)
-----------------------
menu ||| galery
-----------------------
Instead of (I have now):
.................
galery (100 width 100 height)
................
I want (don't work):
var div = document.getElementById("main-block");
var images = div.getElementsByTagName("img");
var slides = Array.prototype.forEach.call(images,function (el) {
slides.push(el.getAttribute("src"));
});
Slider.init({
images : slides
})
Instead of (it is work):
Slider.init(document.body,{
images : [
"http://cdn.trinixy.ru/pics3/20080515/vodopadi_18.jpg",
"http://i.redigo.ru/4fb0dd2a4e202.jpg",
"http://4.bp.blogspot.com/-dN_zBi_BLio/Uli2RStTf2I/AAAAAAAAIH4/EpGnraB6qu8/s1600/%D0%BB%D0%B0%D0%B2%D0%BE%D1%87%D0%BA%D0%B02.jpg",
"http://www.uznayvse.ru/images/stories/uzn_1384119271.jpg",
"http://i.redigo.ru/4fb0dd2a4e202.jpg",
]
});
Also surely there has to be a scrolling down in the browser if the photo is much. In galleries has to be on 3 photos at line.
All my code:
<html>
<head>
<title></title>
<meta charset="utf-8">
</head>
<body>
<center>
<div width="300px" id="content">
<img src="images/top.gif" width="100%" height="300px">
<table border="3px">
<tr>
<td>
<div id="menu">
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<div id="menu_foto">
<li></li><br>
<li></li><br>
<li></li><br>
</div>
</div>
</ul>
</td>
<td>
<div id="main-block">
<img src="images/fotogalery/1.jpg">
<img src="images/fotogalery/2.jpg"><br>
<img src="images/fotogalery/3.jpg">
<img src="images/fotogalery/4.jpg"><br>
<img src="images/fotogalery/5.jpg">
<img src="images/fotogalery/6.jpg"><br>
<img src="images/fotogalery/7.jpg">
<img src="images/fotogalery/8.jpg"><br>
</div>
</td>
</tr>
</table>
</div>
</center>
</body>
</html>
<style>
html,body{
margin:0px;
}
#cap {
width:100%;
height:100%;
background:rgba(0,0,0,0.5);
display:flex;
z-index : 99999;
position:fixed;
}
figure {
padding:0px;
margin:100px auto;
width:800px;
overflow: hidden;
}
img {
height: 450px;
width:550px;
border:5px solid white;
border-radius: 5px;
margin:auto;
}
ul {
width:810px;
list-style:none;
margin:0px;
padding:0px;
}
li {
width:810px;
position:absolute;
opacity:0;
text-align: center;
}
li:first-child{
opacity:1;
}
.previewSlide{
width:250px;
height:250px;
overflow: hidden;
float: left;
margin:10px;
}
</style>
<script>
var Slider = {
Collection : [],
currentSlide : 0,
Box : {
showBox : function (n) {
if(!this.element) return;
this.element.style.display = "flex";
document.body.style.overflow = "hidden";
var slides = this.element.getElementsByTagName("li");
slides.item(n).style.opacity = 1;
Slider.currentSlide = n;
},
closeBox : function (n) {
if(!this.element) return;
this.element.style.display = "none";
document.body.style.overflow = "auto";
var slides = this.element.getElementsByTagName("li");
Array.prototype.forEach.call(slides,function (el) {
el.style.opacity = 0;
})
}
},
Prevew : {
element : {},
init : function (p) {
var div = document.createElement("div");
div.id = "previewSlides";
div.style.position = "fixed";
for(var i in Slider.Collection) {
var figure = document.createElement("figure");
figure.setAttribute("class","previewSlide");
var img = document.createElement("img");
img.src = Slider.Collection[i];
img.onclick = (function (i) {
var i = i;
return function (e) {
Slider.Box.showBox(i);
}
})(i);
figure.appendChild(img);
div.appendChild(figure);
this.element = div;
}
p.appendChild(div)
}
}
}
Slider.init = function (p,options) {
var opt = options || {};
this.Collection = opt.images;
var self = this;
(function (p) {
var cap = document.createElement("div");
cap.id = "cap";
var figure = document.createElement("figure");
figure.id = "slideWrapper";
var ul = document.createElement("ul");
ul.setAttribute("class","slideList");
ul.style.left = 0;
for(var i = 0; i < self.Collection.length; i++) {
var li = document.createElement("li");
var img = document.createElement("img")
img.src = self.Collection[i];
li.appendChild(img);
ul.appendChild(li);
}
var img = document.createElement("img");
img.class = "slide";
img.src = self.Collection[0] || "";
p.appendChild(cap);
cap.appendChild(figure);
figure.appendChild(ul);
self.Box.element = cap;
self.Box.closeBox();
self.Prevew.init(p);
})(p);
}
Slider.changeSlide = function (dir) {
var slides = this.Box.element.getElementsByTagName("li");
var l = this.Collection.length;
slides.item(this.currentSlide).style.opacity = 0;
(dir) ? this.currentSlide ++ : this.currentSlide--;
if(this.currentSlide == l) this.currentSlide = 0;
if(this.currentSlide < 0) this.currentSlide = l-1;
slides.item(this.currentSlide).style.opacity = 1;
};
var div = document.getElementById("main-block");
var images = div.getElementsByTagName("img");
var slides = Array.prototype.forEach.call(images,function (el) {
slides.push(el.getAttribute("src"));
});
Slider.init(document.body,{
images : slides
});
Slider.Box.element.onclick = function (e) {
if(e.target.tagName != "IMG") Slider.Box.closeBox();
else {
if(e.clientX > (e.target.offsetWidth + e.target.style.width/2) ) Slider.changeSlide(false);
else Slider.changeSlide(true);
}
}
</script>
I can't write the whole page for you, so this is surely not a complete answer.
1) Start with the html you find here. It will give your page basically the structure you asked for. When you insert elements for your needs, dont forget to close them properly. 2) Forget the css you have posted, it has not much to do with your html. Write your own css for the elements you have and put it into style-tag in head. 3) Put your script into script-tag at bottom.
I hope this will help you to get the right direction.
<html>
<head>
<title></title>
<meta charset="utf-8">
<style>
#menu {float: left; width: 30%}
#main-block {float: right; width: 70%}
#footer {clear: both;}
/* put your css here */
</style>
</head>
<body>
<div id="content">
<img src="images/top.gif" width="100%" height="300px">
<div id="menu">
<ul>
<li></li>
<li></li>
</ul>
<div id="menu_foto">
<ul>
<li></li><br>
<li></li><br>
<li></li><br>
</ul>
</div>
</div>
<div id="main-block">
<img src="images/fotogalery/1.jpg">
<img src="images/fotogalery/2.jpg"><br>
<img src="images/fotogalery/3.jpg">
<img src="images/fotogalery/4.jpg"><br>
<img src="images/fotogalery/5.jpg">
<img src="images/fotogalery/6.jpg"><br>
<img src="images/fotogalery/7.jpg">
<img src="images/fotogalery/8.jpg"><br>
</div>
</div>
<div id="footer">
<p> Put in here what you want to have in footer</p>
</div>
</body>
<script>
/* put your javascript here */
</script>
</html>

adding current class to automated image changer

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.

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?

Categories

Resources