Onclick enable the clicked image and disable the others images - javascript

I want to create an event with Javascript onclick that will enable the clicked image and will disable others.
For example, if I have 6 pictures, how can I do the following: I want to click any picture for example picture number 3, then picture number 3 will be enabled and the pictures 1,2,4,5,6 will be disabled.
A few seconds after, I want to click on picture number 1, then it will become active and 2,3,4,5,6 will be disabled.
How can I do this?

You can do this using jQuery Siblings
Here an example:
$(function(){
$("img").click(function(){
$(this).addClass("on").siblings("img").removeClass("on");
});
});
Edit, working example:
$(function(){
var replaceImg = function($img){
var src0= $img.attr("src");
var src1= $img.data("on-src");
$img.attr("src",src1).data("on-src",src0);
};
$("img").click(function(){
$(this).addClass("on");
replaceImg($(this));
$(this).siblings("img").each(
function(){
var $this = $(this);
if($this.hasClass("on")){
$(this).removeClass("on");
replaceImg($(this));
}
}
);
});
});
img{border:solid 3px black;}
img.on{border:solid 3px red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<img src="https://67.media.tumblr.com/avatar_0c16e55c511b_128.png" data-on-src="http://icons.iconarchive.com/icons/jonathan-rey/simpsons/128/Homer-Simpson-04-Happy-icon.png">
<img src="https://67.media.tumblr.com/avatar_0c16e55c511b_128.png" data-on-src="http://icons.iconarchive.com/icons/jonathan-rey/simpsons/128/Homer-Simpson-04-Happy-icon.png">
<img src="https://67.media.tumblr.com/avatar_0c16e55c511b_128.png" data-on-src="http://icons.iconarchive.com/icons/jonathan-rey/simpsons/128/Homer-Simpson-04-Happy-icon.png">
<img src="https://67.media.tumblr.com/avatar_0c16e55c511b_128.png" data-on-src="http://icons.iconarchive.com/icons/jonathan-rey/simpsons/128/Homer-Simpson-04-Happy-icon.png">
<img src="https://67.media.tumblr.com/avatar_0c16e55c511b_128.png" data-on-src="http://icons.iconarchive.com/icons/jonathan-rey/simpsons/128/Homer-Simpson-04-Happy-icon.png">
</div>
Edit 2 - For Change the image

Related

Toggle between two images in a long list on click

I have a long list (dynamically created) that can contain only one of two images; red.png or green.png and look like this:
<img src="red.img" id="choice1" onclick=" changeIcon('1')">
<img src="red.img" id="choice2" onclick=" changeIcon('2')">
...
<img src="red.img" id="choiceN" onclick=" changeIcon('N')">
I manage to toggle between red and green by using the following java script:
function changeIcon(line){
var l = "choice".concat(line);
if (document.getElementById(l).src == "red.png")
{document.getElementById(l).src = "green.png";
}else {
document.getElementById(l).src = "red.png";
}
}
What I am trying to do is that when I click on the red image only this (id?) become green and the rest of the list become red and if I click on a green then this become back to red so the entire list is red again.
The concept is similar to the radio buttons but without using form
Well, try using:
var l = "choice" + line;
Or, even better, I would suggest you to change your code this way, using jQuery:
$(function () {
// Replace "body" with some static parent of "img.toggle".
$("body").on("click", ".toggle", function () {
if ($(this).attr("src") == "red.img")
this.src = "green.img";
else
this.src = "red.img";
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<img src="red.img" class="toggle" />
<img src="red.img" class="toggle" />
<img src="red.img" class="toggle" />
As mentioned in the comments, if you want it to act like a radio button, you can use this:
$(function () {
// Replace "body" with some static parent of "img.toggle".
$("body").on("click", ".toggle", function () {
// Reset everything.
$(".toggle").attr("src", "red.img");
this.src = "green.img";
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<img src="red.img" class="toggle" />
<img src="red.img" class="toggle" />
<img src="red.img" class="toggle" />
The same thing can be achieved without using images:
$(function () {
$(".radios").on("click", "span", function () {
$(".radios span").removeClass("active");
$(this).addClass("active");
});
});
.radios span {display: inline-block; width: 12px; height: 12px; border: 1px solid #999; cursor: pointer; border-radius: 100%;}
.radios span.active {border-color: #000; background-color: #666;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radios">
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
To change all the items at once add a class to your images (I'll use a class named img as an example):
<img src="red.png" class="img" id="choice1" onclick=" changeIcon('1')">
<img src="red.png" class="img" id="choice2" onclick=" changeIcon('2')">
...
<img src="red.png" class="img" id="choiceN" onclick=" changeIcon('N')">
Then when you trigger the event change them all to a certain color, and then this to the desired color. Below is an example of when clicking a "red" item, changing the item clicked to green and the rest to red:
$(".img").click(function(){
if( $(this).attr('src') == "red.png" ) {
$(".img").attr('src', "red.png"); // Make them all red
$(this).attr('src', "green.png"); // Change the clicked one to green
}
});
Example Fiddle (Note you will need to look at the src of the images directly to see the changes)
just use class attribute to change whole list to red then this to toggle clicked item
//the jQuery function
function toggleSrc()
{
var nextSrc = "red.png";
if( $(this).attr("src") == "red.png" )
nextSrc = "green.png";
$(".image").attr("src","red.jpg");
$(this).attr("src",nextSrc);
}
//binding function to .image
$( document ).ready(function() {
$(".image").click( toggleSrc );
});
//and the HTML:
<img src="red.png" class="image" id="choice1">
<img src="red.png" class="image" id="choice2">

Reload a DIV on click of another DIV

I have a div called masterdiv, inside this div there are 3 other div div1, div2, and div3,
This is the html for these html:
<div id="masterdiv" class="masterdivclass">
<div id="div1"><img class="div1class" src="image1.jpg" id="div1id" /></div>
<div id="div2"><img class="div2class" src="image2.jpg" id="div2id" /></div>
<div id="div3"><img class="div3class" src="image3.jpg" id="div3id" /></div>
</div>
I also have another div:
<div id=”reload”><img src="reload.png" width="200" height="70" onclick=loadDIV();></div>
What I’m trying to do is to reload the masterdiv div whenever the reload div is clicked on. Hiding and then showing the div isn’t enough as I need the content to be reloaded when the refresh div is clicked on. I don’t want to reload the entire page, just the masterdiv which contains the 3 other div. But I’m not certain this is possible.
I’m trying to do it with this Javascript function:
<script type="text/javascript">
function loadDiv(){
$("<div id="masterdiv" class="masterdivclass">
<div id="div1"><img class="div1class" src="image1.jpg" id="div1id" /></div>
<div id="div2"><img class="div2class" src="image2.jpg" id="div2id" /></div>
<div id="div3"><img class="div3class" src="image3.jpg" id="div3id" /></div>
</div>").appendTo("body");
}
</script>
This isn’t working, I think maybe I'm going about this in the wrong way? Maybe I’m missing something very simple here? I’d really appreciate any help with this, thank you in advance!
UPDATE
After reconsidering my project's requirements, I need to change part of my question, I now need to randomise the images displayed in the divs, and have a new random image load every time the reload div is clicked on. I also need to remove each class that’s currently in each of the three divs and then reattach the same classes to the divs (if I don’t remove and reattach the classes then the divs just display the plain images without any class/effect applied to them, it seems like I need to reload the class every time I load an image into a div in order for the class/effect to be applied successfully).
I have 5 images, and I’m using each div’s id tag to attach a random image to each div.
First I’m assigning the 5 different images to 5 different ids:
<script>
document.getElementById('sample1').src="images/00001.jpg";
document.getElementById('sample2').src="images/00002.jpg";
document.getElementById('sample3').src="images/00003.jpg";
document.getElementById('sample4').src="images/00004.jpg";
document.getElementById('sample5').src="images/00005.jpg";
</script>
And then I’m trying to use the following Javascript to load a randomised id (and its assigned image) to each of the 3 divs when the reload div is clicked:
<script>
$(function() {
$('#reload').on('click',function(){
$("#masterdiv").find("div[id^='div']").each(function(index){
//First, remove and reattach classes “div1class”, “div2class” and “div3class”
//from “easyDIV”, “mediumDIV” and “hardDIV” respectively:
$(“#easyDIV”).removeClass('div1class');
$(“#easyDIV”).addClass('div1class');
$(“#mediumDIV”).removeClass('div2class');
$(“#mediumDIV”).addClass('div2class');
$(“#hardDIV”).removeClass('div3class');
$(“#hardDIV”).addClass('div3class');
//Get a random number between 1 and 5, then attach it to “sample”,
//so that the result will be either “sample1”, “sample2”, “sample3”, “sample4” or “sample5”,
//call this variable “variablesample”:
var num = Math.floor(Math.random() * 5 + 1);
variablesample = "sample" +num;
//Attach this randomised id to all three divs using “variablesample”:
jQuery(this).prev("easyDIV").attr("id",variablesample);
jQuery(this).prev("mediumDIV").attr("id",variablesample);
jQuery(this).prev("hardDIV").attr("id",variablesample);
});
var p = $("#masterdiv").parent();
var el = $("#masterdiv").detach();
p.append(el);
});
});
</script>
I’m trying to make it so that all 3 divs will show the same randomised picture (that’s why they’re all sharing the variable “variablesample”), and each div will reload its own class/effect (div1class, div2class and div3class) but it’s not working. I’m not sure if it’s correct to use jQuery inside a Javascript function, or if my syntax for updating the ids of the divs is incorrect.
Perhaps my logic to solving this problem is all wrong? I’d really appreciate any more help with this problem. Thanks again in advance!
Original question was edited many times, so here is the correct answer for the latest edit. Answer to the question; "How to use random image, but same image on all 3, and 3 class on/off switching":
$(function() {
var imageArray = [
'https://via.placeholder.com/40x40',
'https://via.placeholder.com/80x40',
'https://via.placeholder.com/120x40',
'https://via.placeholder.com/160x40',
'https://via.placeholder.com/200x40'];
reloadImages(imageArray);
$('#reload').on('click',function(){
$( "#masterdiv img[id^='div']" ).each(function(index){
$(this).removeClass("div"+(index+1)+"class");
$(this).fadeOut( "slow", function() {
if(index==0) {
reloadImages(imageArray);
}
$(this).addClass("div"+(index+1)+"class");
$(this).fadeIn();
});
});
});
});
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
function reloadImages(array){
shuffleArray(array);
for(var i=0;i<3;i++){
// places the first image into all divs, change 0 to i if you want different images in each div
document.getElementById('div'+(i+1)+'id').src=array[0];
}
}
.div1class {
border:2px dashed #0F0;
}
.div2class {
border:2px dashed yellow;
}
.div3class {
border:2px dashed red;
}
#reload {
background-color:blue;
color:white;
width:100px;
height:30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='reload'>Click here</div>
<div id="masterdiv" class="masterdivclass">
<div id="div1">
<img src="https://via.placeholder.com/20x40" class="div1class" id="div1id" />
</div>
<div id="div2">
<img src="https://via.placeholder.com/20x40" class="div2class" id="div2id" />
</div>
<div id="div3">
<img src="https://via.placeholder.com/20x40" class="div3class" id="div3id" />
</div>
</div>
Line breaks and un-escaped quotes are why the functions is not working.
function loadDiv(){
$('#masterdiv').remove();
$("<div id='masterdiv' class='masterdivclass'><div id='div1'><img class='div1class' src='image1.jpg' id='div1id' /></div><div id='div2'><img class='div2class' src='image2.jpg' id='div2id' /></div><div id='div3'><img class='div3class' src='image3.jpg' id='div3id' /></div></div>").appendTo("body");
}
try:
function loadDiv(){
$("#masterdiv").load(location.href + " #masterdiv");
}
Here's the code pen demo:
http://codepen.io/anon/pen/xwgRWm
If content of container is not being changed dynamically then there is no point reloading it. appendTo wiil append DOM in existing DOM structure, you will need html() here which will replace the content inside container. Also note you had typo here onclick=loadDiv();
HTML:
<div id="masterdiv" class="masterdivclass">
<div id="div1"><img class="div1class" src="image1.jpg" id="div1id"/></div>
<div id="div2"><img class="div2class" src="image2.jpg" id="div2id"/></div>
<div id="div3"><img class="div3class" src="image3.jpg" id="div3id"/></div>
</div>
<div id="reload"><img src="reload.png" width="200" height="70" onclick=loadDiv();></div>
JS:
function loadDiv() {
$("#masterdiv").html('<div id="div1"><img class="div1class" src="image1.jpg" id="div1id" /></div>\
<div id="div2"><img class="div2class" src="image2.jpg" id="div2id" /></div>\
<div id="div3"><img class="div3class" src="image3.jpg" id="div3id" /></div>');
}

Add add/remove class click picture in queue jQuery

I have those pictures
<img src=img1.jpg class=pic />
<img src=img2.jpg class=pic />
<img src=img3.jpg class=pic />
<img src=img4.jpg class=pic />
<img src=img5.jpg class=pic />
<img src=img6.jpg class=pic />
.ShowBorderRed{border:3px solid red;}
I want to add the class .ShowBorderRed once I click one of them and remove this class once I click another picture and add the class to this new image. JQuery
Use the following:
$(document).ready(function(){
var $img = $('.pic');
$img.click(function(event){
$img.removeClass('ShowBorderRed');
$(this).addClass('ShowBorderRed');
});
});
See the comments inline in the code:
// bind click event on all the images having pic class
$('img.pic').on('click', function() {
$(this).addClass('ShowBorderRed') // Add class to the clicked image
.siblings().removeClass('ShowBorderRed'); // Remove class from other sibling images
});
DEMO
OR
If the images are not siblings:
var $images = $('img.pic');
$images.on('click', function() {
$images.removeClass('ShowBorderRed'); // Remove class from all other images
$(this).addClass('ShowBorderRed'); // Add class to the clicked image
});
DEMO
Use the following code:
$(document).ready(function(){
var $img = $('.pic');
$img.click(function(event){
$img.removeClass('ShowBorderRed');
$(this).addClass('ShowBorderRed');
});
});
refer the below mentioned link.
http://jsfiddle.net/2QyY3/199/

How to use jquery to swap the position of multiple images on click

I'm a novice at jquery/javascript, so apologies in advance if this is a dumb question.
I have 3 images and I want to be able to change their position when a user clicks either the second or the third one. For example, if the user clicks image #2, I want image #2 to become image #1 (left-most), then image #3 becomes image #2 (middle) and finally image #1 becomes image #3 (right-most). If the user clicks image #3, I want image #3 to become image #1 (left-most), then image #1 becomes image #2 (middle) and finally image #2 becomes image #3 (right-most).
If the user clicks the first image, I don't want anything to happen.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>ImageSwap</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var img = new Array("http://i.imgur.com/QWso5yB.png", "http://i.imgur.com/O4X3egC.png", "http://i.imgur.com/w3p2qLp.png");
$('#first').bind('click', firstChannel);
$('#second').bind('click', secondChannel);
});
function firstChannel() {
var tempImg = img[0];
img[1] = img[2];
img[2] = tempImg;
$('#home').attr('src',img[0]);
$('#first').attr('src',img[1]);
$('#second').attr('src',img[2]);
};
function secondChannel() {
var tempImg = img[0];
img[0] = img[2];
img[2] = img[1];
img[1] = tempImg;
$('#home').attr('src',img[0]);
$('#first').attr('src',img[1]);
$('#second').attr('src',img[2]);
};
</script>
</head>
<body>
<img id="home" src="http://i.imgur.com/QWso5yB.png">
<img id="first" src="http://i.imgur.com/O4X3egC.png">
<img id="second" src="http://i.imgur.com/w3p2qLp.png">
</body>
</html>
When clicking the 2nd and 3rd images, nothing happens. What the heck am I doing wrong here? Is there an easier way to do this? I've been pulling my hair out searching everywhere but can't seem to find an answer. Many thanks in advance for any feedback you can give me...
Why not make it simple? jsBin demo
A parent element:
<div id="channels">
<img src="http://i.imgur.com/QWso5yB.png">
<img src="http://i.imgur.com/O4X3egC.png">
<img src="http://i.imgur.com/w3p2qLp.png">
</div>
and some prepend():
$(function () {
var $chn = $("#channels");
$chn.on("click","img", function(){
$chn.prepend( this );
});
});
I mean, if the first image represents the current channel, than all you need to do (as above) is to prepend the clicked element. To style the first element simply use CSS img:first-child
EDIT: KEEP ORDER
jsBin demo with Order
If appending creates at some point a mess of channels order,
I'd suggest you to:
Create a MAIN or currently watching big image and place all channels inside a parent:
<img id="current">
<div id="channels">
<img src="//placehold.it/90x40/a7b&text=1">
<img src="//placehold.it/90x40/ba7&text=2">
<img src="//placehold.it/90x40/7ba&text=3">
<img src="//placehold.it/90x40/bb7&text=4">
<img src="//placehold.it/90x40/77a&text=5">
<img src="//placehold.it/90x40/ab7&text=6">
</div>
Than on a channel-click, set the clicked image src to the BIG image, and hide the clicked one:
$(function () {
var $img = $("#channels").find("img");
var $current = $("#current"); // The big image
$img.on("click", function(){
$current[0].src = this.src;
$img.show();
$(this).hide();
}).eq(0).click();
});
Example with a better UI

Html in-page hidden text that isn't shown until link is clicked

sort of new to html. I'm looking to create animation that when am image is clicked, it plays an animation that splits open a half page of text and in stuff. Something like this: http://sketchtoy.com/62368639
If you want to do things like that, you should really have a look at a javascript framework like jquery (www.jquery.com)
I find this one particularly easy to learn.
For what you want to do:
<div style="display: none;" id="mytext">Your text</div>
<a onclick="$('#mytext').show()"></a>
The basic process is
Add the click handler for the images
Find the last image in the row that the clicked image is in
set the contents of the expanding element
insert the expanding element after the image from step 2
show the expanding element (in this case a slideDown animation)
This is using jQuery library, which you did not tag, but it makes doing this a lot easier. If you need a vanilla javascript approach one can be added.
HTML
<div id="container">
<img src="http://placehold.it/128x128" />
<img src="http://placehold.it/128x128" />
<img src="http://placehold.it/128x128" />
<img src="http://placehold.it/128x64" />
<img src="http://placehold.it/128x64" />
<img src="http://placehold.it/128x64" />
<div id="expander">
<img src="" />
<div id="info">
some info
</div>
</div>
</div>
JS
//Just making the expander half the height of the viewport
var winheight = $(window).height();
$("#expander").css("height",winheight/2);
$("img").click(function(){
var img = $(this);
var src = img.attr("src");
var afterImg = findLastImgInRow(img);
var expander = $("#expander");
//Hide the expander if previously open
expander.hide(0);
//just setting the insides
expander.find("img").attr("src",src);
expander.find("#info").html("This is a test");
//Put the expander after the last image in the row
//so it will appear between its row and the next
expander.insertAfter(afterImg);
expander.slideDown(600);
//This scrolls the page so that it will make the
//expander appear in the middle of the page
$('html, body').animate({
scrollTop: expander.offset().top-(winheight/4)
}, 600);
});
//Function to find the last image
//in a row by comparing their offset top values
function findLastImgInRow(img){
var imgTop = img.offset().top;
var img2 = img;
do{
if( img2.offset().top != imgTop ){
img2 = img2.prev();
break;
}
}while(img2=img2.next());
return img2;
}
JSFiddle Demo

Categories