Replace class in order to replace image on click with jquery - javascript

I read a number of articles and answers here on Stack Overflow but none of them answered my question as I'm really a noob when it comes to jQuery and I'm not sure how to do this.
I have a HTML landing page on which I'm trying to show several images on which you click and they get replaced with another image and when clicked again or at another image the original one is shown.
I have this so far:
<div class="santa">
<img class="show" src="images/santa.png" alt="">
<img class="hide" src="images/bubble.png" alt="">
</div>
.hide { display: none; }
.show { display: block; }
I want to show santa.png by default and when clicked on to change it to bubble.png, meaning default class is show and when clicked on it's hide for santa and vice versa.
Thanks in advance!

The simple way to do this is to call toggle() on both the displayed and hidden images when one is clicked. This will invert the display state of both elements simultaneously:
$('.hide, .show').click(function() {
$(this).closest('div').find('.hide, .show').toggle();
})
.hide { display: none; }
.show { display: block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="santa">
<img class="show" src="images/santa.png" alt="Santa">
<img class="hide" src="images/bubble.png" alt="Bubble">
</div>
<div class="santa">
<img class="show" src="images/santa.png" alt="Santa2">
<img class="hide" src="images/bubble.png" alt="Bubble2">
</div>
If you actually want to change the class values on the elements, then you can use toggleClass() instead:
$('.hide, .show').click(function() {
$(this).closest('div').find('.hide, .show').toggleClass('hide show');
})
.hide { display: none; }
.show { display: block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="santa">
<img class="show" src="images/santa.png" alt="Santa">
<img class="hide" src="images/bubble.png" alt="Bubble">
</div>
<div class="santa">
<img class="show" src="images/santa.png" alt="Santa2">
<img class="hide" src="images/bubble.png" alt="Bubble2">
</div>

Since u are a beginner, my humble request is to learn vanillajs thoroughly before using libraries like jquery.
here is a pure js approach.. Cheers
let santaimg = document.getElementById('santa');
let bubbleimg = document.getElementById('bubble');
santaimg.onclick = showBubbleHideSanta;
function showBubbleHideSanta() {
santaimg.classList += " hide";
//santaimg.classList -= "show";
bubbleimg.classList -= " hide";
//bubbleimg.classList += "show";
}
.show {
display:block;
}
.hide {
display:none;
}
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/4/49/Jonathan_G_Meath_portrays_Santa_Claus.jpg/220px-Jonathan_G_Meath_portrays_Santa_Claus.jpg" id="santa" class="show"/>
<img src = "https://sophosnews.files.wordpress.com/2017/05/shutterstock_296886146.jpg?w=780&h=408&crop=1" id="bubble" class="hide"/>

Try this...if you have two images only...
HTML
<div class="santa">
<img class="show" src="http://via.placeholder.com/350x150" alt="img">
<img class="hide" src="http://via.placeholder.com/250x150" alt="img">
</div>
CSS
.show{
display:block;
}
.hide{
display:none;
}
img{
max-width:100%;
height:auto;
cursor:pointer;
}
JS
jQuery('.show, .hide').click(function() {
jQuery('.show, .hide').toggle();
});
Thanks !

If you want to show/hide an element I suggest you to use .hide() and .show()
It's pure JQuery and no need of CSS.
"The matched elements will be hidden immediately, with no animation. This is roughly equivalent to calling .css( "display", "none" ), except that the value of the display property is saved in jQuery's data cache so that display can later be restored to its initial value"
http://api.jquery.com/hide/
Here is an exemple:
HTML
<div>
<img class="santa_img" src="images/santa.png" alt="santa">
<img class="bubble_img" src="images/bubble.png" alt="bubble">
</div>
JS (JQuery)
$(".santa_img").click(function(){
$(".santa_img").hide();
$(".bubble_img").show();
})
$(".bubble_img").click(function(){
$(".bubble_img").hide();
$(".santa_img").show();
})
$(".bubble_img").hide(); //Hidden by default

Related

How to addClass and removeClass using jQuery on hidden elements on page

This is my html code:
<div class="Image" style="display: block;">1</div>
<div class="Image" style="display: none;">2</div>
<div class="Image" style="display: none;">3</div>
<div class="Image" style="display: none;">4</div>
The display: block property will run from lines 1 through 4 using a other javascript code.
I want to addClass "slide-in" to the line with display: block property and addClass "slide-out" to line with display: none property.
And this is what i want:
<div class="Image slide-in" style="display: block;">1</div>
<div class="Image slide-out" style="display: none;">2</div>
<div class="Image slide-out" style="display: none;">3</div>
<div class="Image slide-out" style="display: none;">4</div>
Is there any way to do that. Please help me, thank you everyone!
Yes its possible. We need to use $.each function of jQuery to get all the elements with class .Image and the check for styles and if its block then we addClass the class slide-in OR else we add class slide-out
In order to check for current styles - We can simply use .css method of jQuery to get the current style of the elements.
Also, to add classes to the hidden element we need virtually show them in the DOM using block > apply class slide-out > hide them again.
Live Working Demo:
$('.Image').each(function(i, el) {
if ($(el).css("display") == 'block') {
$(el).addClass('slide-in') //add Class slide-in
} else {
$(el).css("display", "block") //show them virtually
$(el).addClass('slide-out') //apply class slide-out
$(el).css("display", "none") //hide them again
}
console.log(el) //classes added
})
.slide-in {
background: green;
}
.slide-out {
background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="Image" style="display: block;">1</div>
<div class="Image" style="display: none;">2</div>
<div class="Image" style="display: none;">3</div>
<div class="Image" style="display: none;">4</div>

Displaying a <div> content when loading a page, appears when refreshing

I'm not able to solve this issue, I'm not a professional javascript coder.
I have several buttons displaying a div content. When the page loads, the first div must be visible, but hidden when clicking other buttons. I could make this with a script and works fine.
The problem is when the content showed is different than the first div and the page is refreshed, the first div becomes visible. I know is the logic behavior based on this script, what should I change to show the first div when loading and not when refreshing the page?
$(document).ready(function() {
$("#apa, #com, #adi").click(function() {
if ($('.cover').css('display') == 'block') {
$('.cover').css('display', 'none');
}
});
$("#apa").click(function() {
if ($('.cover').css('display') == 'none') {
$('.cover').css('display', 'block');
}
});
});
.image {
display: none;
}
.image:target {
display: block;
}
.cover {
display: block;
}
div {display:flex; margin: 0 12px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="image01" class="image cover">
<img src="https://www.african.cam.ac.uk/images/secondlevel/dasshills/image_preview">
</div>
<div id="image02" class="image">
<img src="https://data.whicdn.com/images/60436988/large.png">
</div>
<div id="image03" class="image">
<img src="https://www.tawbaware.com/maxlyons/crop_8.jpg">
</div>
<div>
<div id="apa">
Picture 1
</div>
<div id="com">
Picture 2
</div>
<div id="adi">
Picture 3
</div></div>

Same javascript event for different images?

I have an image that when hover, a div with an overlay will fade in and out.
<div id="img-one">
<div id="overlay-one">
<div class="card-overlay-text">
<p>Enlarge Image<p></div>
</div>
<img src="assets/img/card_one.jpg" alt="" />
</div>
However, I have multiple images and I need to repeat this code for each of these images (assigned with different div's id). How can I get, when hover on specific image.
The code only run on individual image only?
$(function() {
$('#img-one').hover(function() {
$('#overlay-one').stop(true,true).fadeIn();
}, function() {
$('#overlay-one').stop(true,true).fadeOut();
});
});
Use general class in all the image containers div's and overlay div's, like :
<div id="img-one" class='img-container'>
<div id="overlay-one" class='overlay'>
...
</div>
</div>
Then adjust you JS code to invoke just related overlay :
$(function() {
$('.img-container').hover(function() {
$('.overlay', this).stop(true,true).fadeIn();
}, function() {
$('.overlay', this).stop(true,true).fadeOut();
});
});
Hope this helps.
$(function() {
$('.img-container').hover(function() {
$('.overlay', this).stop(true,true).fadeIn();
}, function() {
$('.overlay', this).stop(true,true).fadeOut();
});
});
.img-container{
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='img-container'>
<div class='overlay'>
<div class="card-overlay-text">
<p>Enlarge Image 1<p></div>
</div>
</div>
<div class='img-container'>
<div class='overlay'>
<div class="card-overlay-text">
<p>Enlarge Image 2<p></div>
</div>
</div>
<div class='img-container'>
<div class='overlay'>
<div class="card-overlay-text">
<p>Enlarge Image 3<p></div>
</div>
</div>
You'll better use classes. Then do something like this:
$('.main-container').find('.div-class-name').forEach(function(el) {
<bind a handler for each consequent element here>
});
You'll end up with a bunch of handlers that are bound to each individual ".div-class-name" element.
It is recommended to use classes because that is what classes are for and id's are not.
If your case demands some situation where you have no control over the HTML part, you can use wildcards in attribute selectors in some cases. Like div[id^=overlay] to selects all div with id starting with overlay
$(function() {
$('div[id^=img]').hover(function() {
$('div[id^=overlay]',this).stop(true,true).fadeIn();
}, function() {
$('div[id^=overlay]',this).stop(true,true).fadeOut();
});
});
div[id^=img]{
position: relative;
height:100px;
width:100px;
border:1px solid black;
margin:2px;
}
div[id^=img] > div[id^=overlay]{
position:absolute;
background:rgba(0,0,0,.2);
top:0;
left:0;
right:0;
bottom:0;
display:none;
width:100px;
color:#fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="img-one">
<div id="overlay-one">
<div class="card-overlay-text">
<p>Enlarge Image 1<p></div>
</div>
<img width="100" src="https://upload.wikimedia.org/wikipedia/commons/e/ed/Raff_House.jpg" alt="" />
</div>
<div id="img-two">
<div id="overlay-two">
<div class="card-overlay-text">
<p>Enlarge Image 2<p></div>
</div>
<img width="100" src="https://upload.wikimedia.org/wikipedia/commons/e/ed/Raff_House.jpg" alt="" />
</div>
You can try with the jQuery Easy Overlay Plugin
http://eivissapp.github.io/jquery-easy-overlay/
In the code, you should assign a class to the images, and call this statement (that will work for each image):
jQuery("img.yourclass").hover(function(){
jQuery(this).easyOverlay("start");
}, function(){
jQuery(this).easyOverlay("stop");
});
If you have fontawesome in the page, then execute this before the code above (otherwhise the plugin will use the fontawesome spinner inside the overlay div):
jQuery.fn.easyOverlay.options = { spin: false }

Simplify this javascript for Show one, Hide Rest

I am using a script for a gallery in which clicking on an element in the navigation shows only one div, but hides the others.
Currently my script is very specific, as I need to add a new function for every possible instance. See below... You can imagine this grows out of control easily the more images are added.
Can someone help me make this code more generic and elegant? I'm not very experienced with Javascript/JQuery but this is getting a bit embarrassing lol
So in case it's not clear from the code: the #li1, #li2, #li3 etc are the navigational thumbnails which are always visible. The #img1, #img2, #img3 etc. are the variable displayed divs. When one is visible, the rest should be hidden.
Additional questions:
for every #img1 displayed, I'd like to also show a title in a separate div, let's say #title1, #title2, etc. How do I do this? So eg clicking #li1 would show #img1 and #title1 but hide all other #img.. and #title..
all #'s contain images. I've noticed that when one of the images is broken, the whole script stops working properly (all #img.. divs show at once). Why is that?
this script doesn't actually hide all the images until everything is loaded, which you don't notice when running the HTML locally, but you do when you're waiting for the images to download. I'm suspecting because the $("#li1").load(function() refers to a div that is further down in the document. How can I counter this?
I hope I'm not asking too much, I've tried to understand this myself but I can't figure it out.
$("#li1").load(function() {
$("#img2, #img3, #img4, #img5, #img6, #img7, #img8, #img9, #img10, #img0, #intro").hide();
$("#img1").show();
});
$("#li1").on('click', function() {
$("#img2, #img3, #img4, #img5, #img6, #img7, #img8, #img9, #img10, #img0").hide();
$("#img1").show();
});
$("#li2").on('click', function() {
$("#img1, #img3, #img4, #img5, #img6, #img7, #img8, #img9, #img10, #img0").hide();
$("#img2").show();
});
$("#li3").on('click', function() {
$("#img2, #img1, #img4, #img5, #img6, #img7, #img8, #img9, #img10, #img0").hide();
$("#img3").show();
});
etc.
I would probably try something like this:
Thumbnails like:
<li class="thumbnail" data-imageId="0">
...thumbnail...
</li>
<li class="thumbnail" data-imageId="1">
...thumbnail...
</li>
<li class="thumbnail" data-imageId="2">
...thumbnail...
</li>
Images like:
<div class="image" data-imageId="0">
...image...
</div>
<div class="image" data-imageId="1" style="display: none;">
...image...
</div>
<div class="image" data-imageId="2" style="display: none;">
...image...
</div>
<!-- The style attribute in these element hides the element by default,
while still allowing jQuery to show them using show(). -->
And then the JS:
$(".thumbnail").click(function() {
// Hides all images.
$(".image").hide();
// Shows appropriate one.
var imageId = $(this).data("imageId"); // Fetches the value of the data-imageId attribute.
$(".image[data-imageId="+imageId+"]").show();
});
I see that your li's have ids of 'li1', 'li2', etc. Assign them all a specific class, like 'liLinks'.
Then, add an event handler for that class like this:
$(".liLinks").click(function(){
var ImageToShow = $(this).prop("id").replace("li", ""); // This gets the number of the li
for (i=0; i<= 10; i++){ //or however many images you have
if (i != ImageToShow)
$("#img" + i).hide();
else
$("#img" + i).show();
}
});
Oh, and you can show and hide any other elements with the same method used above. Just make sure their naming convention is the same, and you should be all set!
So, I have two solutions for you:
First option: Edit the HTML code to fix this logic:
<li class="nav" data-image="0">0</li>
<li class="nav" data-image="1">2</li>
<li class="nav" data-image="2">3</li>
...
...and so on.
Now the JavaScript code will be pretty short and easy, here it is:
function showOne(e) {
var max = 5, // assuming that there are 5 images, from #img0 to #img4
toShow = e.target.dataset.image;
for (var i=0; i < max; i++) {
if (i == toShow) $('#img'+i).hide();
else $('#img'+i).show();
}
}
$('.nav').bind('click', showOne);
If your logic isn't this one then i suggest you to edit the HTML to fix this logic, which is the easiest way to do what you want.
Second option: I am assuming that you use a logic like this:
#li0 shows #img0
#li1 shows #img1
#li2 shows #img2
...
#liN shows the Nth img of the array
Here's the code then:
function showOne() {
var max = 4, // assuming that there are 5 images, from #img0 to #img4
toShow = this.id.substr(2);
$('#img'+toShow).show();
for (var i=0; i < max; i++) {
if (i != toShow) $('#img'+i).hide();
}
}
$('#li0, #li1, #li2, #li3, #li4').bind('click', showOne);
In this snippet I only used 5 images, but you can add more images changing the max value and adding the relative li elements in the $('#li0, #li1, ...) selector.
Just hide all of them with CSS, then override the one you care about to show.
<!doctype html>
<html>
<head>
<style type="text/css">
#showbox img { display: none; width: 300px; }
#showbox.show1 img#img1,
#showbox.show2 img#img2,
#showbox.show3 img#img3,
#showbox.show4 img#img4 { display: block; }
</style>
</head>
<body>
<div id="showbox" class="3">
<img id="img1" src="http://upload.wikimedia.org/wikipedia/commons/6/6f/ChessSet.jpg">
<img id="img2" src="http://upload.wikimedia.org/wikipedia/commons/c/c3/Chess_board_opening_staunton.jpg">
<img id="img3" src="http://www.umbc.edu/studentlife/orgs/chess/images/News%20and%20Events/chess_sets.jpg">
<img id="img4" src="http://upload.wikimedia.org/wikipedia/commons/thumb/9/97/Russisches_festungsschach.PNG/350px-Russisches_festungsschach.PNG">
</div>
<input onchange="document.getElementById('showbox').className = 'show' + this.value;">
</body>
</html>
Your images is not hidden while the images is loading because you didn't use
$(function () {
$("imgs").hide ();
});
This function is excuted when the DOM (HTML) is loaded not the images.
The code will be "HTML":
link1
link2
link3
...
jQuery:
$(function () {
$(".img").hide ();
$(".nav").click (function (e) {
$(".img").show ();
});
});
As you might expect you need to change this code to be more progressive but you now get the idea of making them hidden when the page finish liading not when the images finish downloading. And good luck ;) .
var $img = $('#images img'); /* Cache your selector */
$('#nav li').click(function(){
$img.fadeOut().eq( $(this).index() ).stop().fadeIn();
});
#images{ position:relative; }
#images img{ position:absolute; left:0; }
#images img + img {display:none; } /* hide all but first */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id=nav>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<div id=images>
<img src="//placehold.it/50x50/cf5" alt="">
<img src="//placehold.it/50x50/f0f" alt="">
<img src="//placehold.it/50x50/444" alt="">
</div>
Following is an approach:
Add special classes to identify images.
Use classes to show/hide image like: .showing{display:block;}
Use data attribute to store title like: data-title="title"
Add class to identify li and mark selected li with another class like active
$(function() {
$("li.switch").click(function() {
var liActive = $("li.active");
var imgActive = liActive.data("image");
$(imgActive).removeClass("showing").addClass("hidden");
$(liActive).removeClass("active");
//currently clicked li
var $this = $(this);
$this.addClass("active");
var d = $this.data("image");
$(d).removeClass("hidden").addClass("showing");
$("#imgTitle").text($(d).data("title"));
});
});
.gallery {
width: 250px;
height: 250px;
padding: 10px;
}
img {
height: 200px;
width: 200px;
margin: auto auto;
}
.hidden {
display: none;
}
.showing {
display: inline-block;
}
ul {
list-style: none none outside;
display: inline;
}
li {
list-style: none none outside;
display: inline-block;
padding: 3px 6px;
border: 1px solid grey;
color: #0f0;
cursor: pointer;
}
li.active {
border: 2px solid red;
background-color: #c0c0c0;
color: #f00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="gallery">
<img src='https://c2.staticflickr.com/4/3862/15320672416_65b28179b4_c.jpg' class='gimage showing' id='img1' data-title="This is image 1" />
<img src='https://c2.staticflickr.com/4/3893/15156335390_16e16aa1c9_c.jpg' class='gimage hidden' id='img2' data-title="This is image 2" />
<img src='https://c1.staticflickr.com/3/2942/15341799225_09d0f05098_c.jpg' class='gimage hidden' id='img3' data-title="This is image 3" />
<img src='https://c2.staticflickr.com/4/3907/15339877992_695dd1daae_c.jpg' class='gimage hidden' id='img4' data-title="This is image 4" />
<img src='https://farm3.staticflickr.com/2942/15333547162_325fefd6d1.jpg' class='gimage hidden' id='img5' data-title="This is image 5" />
</div>
<div id="imgTitle"></div>
<ul>
<li class="switch active" id="li1" data-image="#img1">1</li>
<li class="switch" id="li1" data-image="#img2">2</li>
<li class="switch" id="li1" data-image="#img3">3</li>
<li class="switch" id="li1" data-image="#img4">4</li>
<li class="switch" id="li1" data-image="#img5">5</li>
</ul>
Try it in this fiddle
Fix from Ricardo van den Broek's code, because
var imageId = $(this).data("imageId");
is seem doesn't work. It's returns "Undefined". So we need to change it to
var imageId = $(this).attr("data-imageId");
Here is all the code,
HTML (Thumbnail section)
<ul>
<li class="thumbnail" data-imageId="0">
Thumbnail 0
</li>
<li class="thumbnail" data-imageId="1">
Thumbnail 1
</li>
<li class="thumbnail" data-imageId="2">
Thumbnail 2
</li>
</ul>
HTML (Image section)
<div class="image" data-imageId="0">
Image 0
</div>
<div class="image" data-imageId="1" style="display: none;">
Image 1
</div>
<div class="image" data-imageId="2" style="display: none;">
Image 2
</div>
JavaScript (jQuery)
$(".thumbnail").click(function() {
$(".image").hide();
// Shows the appropriate one.
var imageId = $(this).attr("data-imageId");
$(".image[data-imageId="+imageId+"]").show();
});

Adding Next and Prev button to my slide

I would like to add a next and previous button to my image slider, but I don't know how to do.
Plz help. I have a basic structure..?
Here is my code..
HTML
<div class="large-photo">
<img src="images/large-photo/photo1.jpg" class="active">
<img src="images/large-photo/photo2.jpg">
</div>
<div class="small-photo">
<img src="images/small-photo/photo1.jpg" class="thumb selected">
<img src="images/small-photo/photo2.jpg" class="thumb">
</div>
<div class="arrow">
<div class="left-arrow"></div>
<div class="right-arrow"></div>
</div>
CSS
.large-photo img {
display: none;
}
.large-photo img.active {
display:block;
}
.small-photo img.selected {
border: 3px solid red;
}
JAVASCRIPT
function loadPhoto() {
$('.small-photo img').click(function() {
$('.selected').removeClass('selected');
var index = $(this).index();
$('.large-photo img.active').removeClass('active');
$('.large-photo img').eq(index).addClass('active');
$(this).addClass('selected');
});
it was some difficult for me to understand what you want as preer according to your code but however you will under stand how this sytem works and also how to use it differently. CODE:
<style type="text/css">
#container{
width: 266px ;
height:128px ;
overflow: hidden;
}
</style>
<script type="text/javascript" src="jquery-2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#left-arrow").click(function(){
$(".small-photo").fadeIn();
$(".large-photo").fadeOut();
});
$("#right-arrow").click(function(){
$(".small-photo").fadeOut();
$(".large-photo").fadeIn(1000);
});
});
</script>
<div id="container">
<div class="large-photo">
<img src="images/1395924816_personal-information.png">
<img src="images/1395938204_lock.png">
</div>
<div class="small-photo">
<img src="images/1395939936_application-pgp-signature.png" >
<img src="images/1396010974_button-cross_basic_red.png" >
</div>
</div>
<div class="arrow">
<-
->
</div>
and yes i had to do some of the major chages such as removing CSS but you can add but for my convinence i removed it just to show you how to do what you want i also change some of the class to id.. etc and also change pictures and you replace all thos pictures to your pictures..
working demo

Categories

Resources