How to show first image of gallery on hover, in different element - javascript

I'm stuck with this for a while and can't find any solution helping me out.
To give an idea of what's going on: I have a li containing an a element and a gallery div which will show up in #thumb on click on a. ( I cut this part out of the code for now)
I want the first image of the gallery to be visible when hovering a. If there is no content in the gallery, i want nothing to happen.
How can I achieve this in plain js? I got quite far but I'm missing the js knowledge (hence all the var's i guess :-). Help is very much appreciated.
The gallery's are automatically generated, so the amount of gallery-#'s depends on the amount of gallery's added via CMS.
JS Fiddle here
var hoverThis = document.getElementsByClassName("project-item");
var galleryId = document.querySelector(".open-gallery").getAttribute("href");
var getFirstImg = document.querySelector(galleryId).firstElementChild.getAttribute("href");
var thumb = document.getElementById('thumb');
var content = getFirstImg.includes("http");
if (content == true) {
hoverThis.addEventListener("mouseover", function(e) {
e.target.thumb.innerHTML = '<img src="' + getFirstImg + '" class="thumb-img">"';
}, false);
hoverThis.addEventListener("mouseout", function(e) {
e.target.thumb.innerHTML = '';
}, false);
} else {
console.log('empty')
};
li {
list-style: none;
}
#thumb {
height: 300px;
width: 300px;
background: beige;
}
.hidden {
display: none
}
img {
height 200px;
width: 200px;
}
<ul>
<li class='project-item'>
<a href="#gallery-1" class="open-gallery">
<span>01.11.17</span>
</a>
<div id="gallery-1" class="hidden">
Image 3
Image 2
</div>
</li>
<li class='project-item'>
<a href="#gallery-2" class="open-gallery">
<span>02.11.17</span>
</a>
<div id="gallery-2" class="hidden">
<!-- empty gallery -->
</div>
</li>
<li class='project-item'>
<a href="#gallery-3" class="open-gallery">
<span>03.11.17</span>
</a>
<div id="gallery-3" class="hidden">
<a href="http://placehold.it/200x20
0">Image 1</a>
Image 2
Image 3
</div>
</li>
</ul>
<div class="thumb-wrap">
<figure id="thumb">
</figure>
</div>

Related

Javascript: Combine hover and click events

I have VERY recently started coding and been asked to code our company website from scratch.
I have coded a team page on the website with a PNG of each member of the team. At the moment when the user hovers over any of the PNGs they turn into a little animated GIF of them waving/doing something.
This is the javascript:
$(document).ready(function()
{
$("#imgAnimateBeth").hover(
function(){
this.src = "images/Team/Videos/Beth.gif";
},
function(){
this.src = "images/Team/Static-shots/Beth.png";
}
);
});
The issue I am having is that I also want to introduce a click state that would bring up a popup with a video of that person and their job description but I can't get it to work.
I have tried creating a CSS overlay but it refuses to work alongside the hover effect (JavaScript) so my assumption is that they don't play well together (??).
Below is the HTML for the section above. Can anyone enlighten me as to how this could be done? Simple language please!
<div class="teamsection">
<img src="images/Team/Static-shots/Beth.png" id="imgAnimateBeth">
<img src="images/Team/Static-shots/Kiemia.png" id="imgAnimateKiemia">
<img src="images/Team/Static-shots/Emma-B.png" id="imgAnimateEmmaB">
<img src="images/Team/Static-shots/Mathew.png" id="imgAnimateMathew">
<img src="images/Team/Static-shots/Sydney.png" id="imgAnimateSydney">
<img src="images/Team/Static-shots/Liz.png" id="imgAnimateLiz">
<img src="images/Team/Static-shots/Russ.png" id="imgAnimateRuss">
<img src="images/Team/Static-shots/Jill.png" id="imgAnimateJill">
<img src="images/Team/Static-shots/Merry.png" id="imgAnimateMerry">
<img src="images/Team/Static-shots/Caroline.png" id="imgAnimateCaroline">
<img src="images/Team/Static-shots/Charlotte.png" id="imgAnimateCharlotte">
<img src="images/Team/Static-shots/Lucien.png" id="imgAnimateLucien">
<img src="images/Team/Static-shots/Sarah.png" id="imgAnimateSarah">
<img src="images/Team/Static-shots/Emma-S.png" id="imgAnimateEmmaS">
<img src="images/Team/Static-shots/David.png" id="imgAnimateDavid">
<img src="images/Team/Static-shots/Kathryn.png" id="imgAnimateKathryn">
</div>
Also, if you need me to upload anything else, just shout.
The CSS overlay was like this:
The CSS code overlay was like this:
.popup {
display: none;
position: fixed;
padding: 30px 70px;
width: 700px;
height: 100%;
z-index: 20;
left: 50px;
top: 20px;
background: rgba(0, 0, 0, 0.9);
overflow: scroll;
}
With a little bit of Javascript:
$ = function(id) {
return document.getElementById(id);
}
var show = function(id) {
$(id).style.display ='block';
}
var hide = function(id) {
$(id).style.display ='none';
}
And I basically did this to the HTML:
<div>
<a href="javascript:void(0)" onclick="show('beth')">
<img src="images/Team/Static-shots/Beth.png" id="imgAnimateBeth">
</a>
</div>
<div class="popup" id="beth">
<div class="close-button">
<i class="fa fa-times" aria-hidden="true"></i> Close
</div>
<h4>CONTENT HERE</h4>
</div>
Maybe this will give you some ideas:
var members = document.querySelectorAll('.team-member');
members.forEach(function(member) {
member.addEventListener('mouseenter', memberShowGIF);
member.addEventListener('mouseleave', memberShowPNG);
member.addEventListener('click', memberVideo);
});
function memberShowGIF(event) {
this.src = this.dataset.gif;
}
function memberShowPNG(event) {
this.src = this.dataset.png;
}
function memberVideo(event) {
console.log('The video thing for: ' + this.id);
}
<div class="teamsection">
<img id="Beth" class="team-member"
src="https://via.placeholder.com/200?text=Beth.png"
data-png="https://via.placeholder.com/200?text=Beth.png"
data-gif="https://via.placeholder.com/200?text=Beth.gif">
<img id="Kiemia" class="team-member"
src="https://via.placeholder.com/200?text=Kiemia.png"
data-png="https://via.placeholder.com/200?text=Kiemia.png"
data-gif="https://via.placeholder.com/200?text=Kiemia.gif">
</div>
The most important learnings here are:
querySelectorAll (as a vanilla alternative to jQuery for selecting nodes)
addEventListener
Data attributes

jQuery change z-index with data-*

I have divs that all occupy the same space, and I want to set up jQuery that has one div come on top of the other as different tabs are clicked. I assume this has to be done by changing the z-index attribute using a data-* attribute that connects the tab to the div.
/*The tabs to be clicked*/
<ul class="tabs">
<li class="tab" data-tabcontainer-id="websites" style="background-color:#1aa3ff;">Websites</li>
<li class="tab" data-tabcontainer-id="sitemaps">Sitemaps</li>
<li class="tab" data-tabcontainer-id="pages">Pages</li>
</ul>
/*The divs that need to come on top of each other*/
<div id="websites" class="tabcontainer">Websites</div>
<div id="sitemaps" class="tabcontainer">Sitemaps</div>
<div id="pages" class="tabcontainer">Pages</div>
DEMO
http://plnkr.co/edit/aNomjINfbYYrRUhMj63A?p=preview
This is how you can change the z-index property using the data attribute.
JS:
jQuery(document).ready(function(){
$('.tab').click(function(){
var target = $(this).data('tabcontainer-id');
$('.tabcontainer').css('z-index', '0'); //resets z-index to 0 for all other
$('.tabcontainer#'+target).css('z-index', '1'); //sets z-index for current target to 1
})
});
I wrote the answer just to meet what you were asking. But reading your question I think you should have a look at the tabs feature by jQuery UI. May be it will help.
https://jqueryui.com/tabs/
madalin ivascu's answer is quite right according to me.
May be bit off the topic, but you can use Jquery UI for the tabs. Easy to implement and work with.
You don't need to worry about managing the z-index in this case. But it might not be appropriate for your case.
<div id="tabs">
<ul >
<li>Websites</li>
<li>Sitemaps</li>
<li>Pages</li>
</ul>
<div id="websites" class="tabcontainer">Websites</div>
<div id="sitemaps" class="tabcontainer">Sitemaps</div>
<div id="pages" class="tabcontainer">Pages</div>
</div>
Fiddle : https://jsfiddle.net/uxwyj4d4/
better go with toggle display:block/none
$('.tabcontainer').not('.tabcontainer:first').hide();
$('.tab').click(function(){
//toggle active class on tabs
$('.tab').removeClass('active');
$(this).addClass('active');
//show corresponding tab container
var id = '#'+$(this).attr('data-tabcontainer-id');
$('.tabcontainer').hide();//here you can go with another class like above that will toggle between block and none
$(id).show();
});
demo:http://plnkr.co/edit/gPIwv80vUIUTQ46Bderj?p=preview
Example for showing tabs using vanilla js, no jQuery is required.
This example use only display instead of z-index.
// get tabs
var targets = {
websites: document.getElementById('websites'),
sitemaps: document.getElementById('sitemaps'),
pages: document.getElementById('pages')
},
show = function(target) {
hideAll();
targets[target.dataset.tabcontainerId].style.display = '';
},
hideAll = function() {
// hide all tabs
Object.keys(targets).forEach(function(key) {
targets[key].style.display = 'none';
});
};
// when click on link show tab
document.getElementById('w').addEventListener('click', function(event) {
show(event.target);
});
document.getElementById('s').addEventListener('click', function(event) {
show(event.target);
});
document.getElementById('p').addEventListener('click', function(event) {
show(event.target);
});
#websites,
#sitemaps,
#pages {
position: absolute;
top: 150px;
width: 100px;
height: 100px;
}
#websites {
background-color: red;
}
#sitemaps {
background-color: blue;
}
#pages {
background-color: green;
}
<ul class="tabs">
<li id="w" class="tab" data-tabcontainer-id="websites" style="background-color:#1aa3ff;">Websites</li>
<li id="s" class="tab" data-tabcontainer-id="sitemaps">Sitemaps</li>
<li id="p" class="tab" data-tabcontainer-id="pages">Pages</li>
</ul>
<div id="websites" class="tabcontainer">Websites</div>
<div id="sitemaps" class="tabcontainer">Sitemaps</div>
<div id="pages" class="tabcontainer">Pages</div>

Scroll to top of a specific class within a scrollable div - on each click of up/down button

I have an RSS blog feed (hidden overflow) with buttons on the top and bottom of the div which will smoothly scroll through-out the feed. I'm looking for a way so that on each button click, it will scroll to the top of the next 'rss-item' (class). The div looks like this:
So what I'm trying to achieve is so each time you click the down arrow (or up) the scroll will stop when each 'rss-item' is at the top of the div.
I explored many similar questions but couldn't quite achieve what I wanted.
Here is the function used to smooth scroll within the div:
$(document).ready(function() {
var scrollTime = 900;
$('#upClick').click(function() {
$('#homeBlogs').animate({
scrollTop: $('#homeBlogs').scrollTop() + 200
}, scrollTime);
});
$('#downClick').click(function() {
$('#homeBlogs').animate({
scrollTop: $('#homeBlogs').scrollTop() - 200
}, scrollTime);
});
});
Here is a screen grab of the generated source html:
Ok, so I re-created this as best I could in a jsfiddle. Here is the HTML structure. I've tried to build this according to the screenshot so they should be similar. Note: I've added a CSS class of "active" to the first "rss-item". This should only be applied in HTML to the first item and needs to stay here in order for the Javascript portion to function correctly.
<div id="blogSection">
<div class="row" id="scrollUp">
<button class="scrollButton" id="upClick">Scroll Up</button>
</div>
<div id="homeBlogs">
<div class="rss-box">
<p class="rss-title"></p>
<ul class="rss-items">
<li class="rss-item active">
<p>ContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContent</p>
<p>ContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContent</p>
<p>ContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContent</p>
</li>
<li class="rss-item">
<p>ContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContent</p>
<p>ContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContent</p>
<p>ContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContent</p>
</li>
<li class="rss-item">
<p>ContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContent</p>
<p>ContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContent</p>
<p>ContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContent</p>
</li>
<li class="rss-item">
<p>ContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContent</p>
<p>ContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContent</p>
<p>ContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContent</p>
</li>
<li class="rss-item">
<p>ContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContent</p>
<p>ContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContent</p>
<p>ContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContent</p>
</li>
<li class="rss-item">
<p>ContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContent</p>
<p>ContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContent</p>
<p>ContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContent</p>
</li>
</ul>
</div>
</div>
<div id="scrollDown" class="row">
<button class="scrollButton" id="downClick">Scroll Down</button>
</div>
</div>
Next, here is the CSS I used. This is purely to support the demo. I set it up so whichever "rss-item" has the "active" class will be highlighted in red. This should hopefully provide a visual cue as to what's going on when a button is clicked.
button {
display: block;
width: 100%;
background-color: black;
color: white;
height: 50px;
cursor: pointer;
}
#scrollUp {
position: fixed;
top: 0;
left: 0;
width: 100%;
}
#scrollDown {
position: fixed;
bottom: 0;
left: 0;
width: 100%;
}
.active {
color: red;
}
Finally, here is the Javascript I used in order to get things done. I've changed it a lot to help make things more efficient and to correct some errors.
$(document).ready(function() {})
//we can use one single event and modify the behavior based on the direction that was clicked
.on('click', '.scrollButton', function() {
var scrollTime = 900,
direction = $(this).attr('id'),
$currentItem = $('.rss-item.active'),
$newItem;
switch (direction) {
case 'upClick':
$newItem = $currentItem.prev('.rss-item');
break;
case 'downClick':
$newItem = $currentItem.next('.rss-item');
break;
}
//if we aren't at the top or bottom of the list already
if ($newItem.length > 0) {
//since we know we can now change the active item, we need to remove this class so we can apply it to the new item
$('.rss-item').removeClass('active');
$newItem.addClass('active');
}
//Now that the logic is out of the way, we can run the scroll animation
//Also, I think you will want to use 'html, body' as a selector so the page itself moves
$('html, body').animate({
scrollTop: $('.rss-item.active').offset().top - 200 //this will keep content positioned correctly, but you shouldn't need both a '+ 200' and '- 200' here. Adjust this value as needed.
}, scrollTime);
});
Finally, here is the jsfiddle: https://jsfiddle.net/sm1215/sebgbnr4/

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 changing text onclick to JavaScript gallery

I'm trying to set up a simple gallery with thumbnails and a main content section. When a thumbnail is clicked, I would like a larger version of the image along with text to display in the main content section. I've got the code for the images down, but can't figure out how to add text on each click. I haven't started doing any styling yet, but the basic code is below. Any help would be much appreciated.
Thanks!
JavaScript:
var mainImg = document.getElementById('Main');
document.getElementById('One').onclick = function() {
mainImg.src = 'http://cdn.shopify.com/s/files/1/0176/5914/files/Kaylee_Radzyminski.jpg?7297';
mainImg.innerHTML = imagetitle;
//alert('one clicked');
};
document.getElementById('Two').onclick = function() {
mainImg.src = 'http://cdn.shopify.com/s/files/1/0176/5914/files/Mason_Hunter_Thornal.jpg?7297';
mainImg.innerHTML = 'imagetitle';
//alert('two clicked');
};
document.getElementById('Three').onclick = function() {
mainImg.src = 'http://cdn.shopify.com/s/files/1/0176/5914/files/Joseph_Nunez_4afb23ac-d71e-42a0-9366-ac78d65deaf4.jpg?7297';
//alert('two clicked');
};
CSS:
#One, #Two, #Three {
width:100px;
opacity: .5; /* css standard */
filter: alpha(opacity=50); /* internet explorer */
}
#One:hover, #Two:hover, #Three:hover {
width:100px;
opacity: 1; /* css standard */
filter: alpha(opacity=100); /* internet explorer */
}
HTML:
<img id="Main" src="http://cdn.shopify.com/s/files/1/0176/5914/files/Kaylee_Radzyminski.jpg?7297" alt="" />
<img id="One" src="http://cdn.shopify.com/s/files/1/0176/5914/files/Kaylee_Radzyminski.jpg?7297" alt="" />
<img id="Two" src="http://cdn.shopify.com/s/files/1/0176/5914/files/Mason_Hunter_Thornal.jpg?7297" alt="" />
<img id="Three" src="http://cdn.shopify.com/s/files/1/0176/5914/files/Joseph_Nunez_4afb23ac-d71e-42a0-9366-ac78d65deaf4.jpg?7297" alt="" />
http://jsfiddle.net/f9B8H/72/
Let's clean this up a bit.
HTML
<div id="container">
<img id="Main" src="http://cdn.shopify.com/s/files/1/0176/5914/files/Kaylee_Radzyminski.jpg?7297" alt="" />
<p id="caption"></p>
</div>
<img id="One" src="http://cdn.shopify.com/s/files/1/0176/5914/files/Kaylee_Radzyminski.jpg?7297" alt="I'm a soldier" />
<img id="Two" src="http://cdn.shopify.com/s/files/1/0176/5914/files/Mason_Hunter_Thornal.jpg?7297" alt="My family" />
<img id="Three" src="http://cdn.shopify.com/s/files/1/0176/5914/files/Joseph_Nunez_4afb23ac-d71e-42a0-9366-ac78d65deaf4.jpg?7297" alt="Dad" />
Notice how I've stored the caption in the alt attribute. A data attribute could also work.
JAVASCRIPT
function displayImage() {
var mainImg = document.getElementById('Main');
var caption = document.getElementById('caption');
mainImg.src = this.src;
caption.innerHTML = this.alt;
}
document.getElementById('One').onclick = displayImage;
document.getElementById('Two').onclick = displayImage;
document.getElementById('Three').onclick = displayImage;
Fiddle: http://jsfiddle.net/g2hY4/
The simplified function works so well because you are using the same image for thumbnail as main image. If you didn't do that, we could store the big image address in a data attribute also.
Here's one way to load the first caption when the page loads. Put it after the code I've already shown you:
displayImage.call(document.getElementById('One') );
You can read about call here. In a nutshell, it redefines the value of this in the displayImage function.
New fiddle
Something to think about is where you want the caption and how it's styled can be set in CSS. I've left that to you also. Absolute positioning will work if the positioning of #container is set to relative.
My implementation gets the text from the attribute alt(could be title) I think this way can be more elegant
document.getElementById('textSubtitle').innerHTML = this.alt;
http://jsfiddle.net/WKfc5/
If you are okay with using jQuery, here is something that I made up real quick. I hope it is useful. [Fiddle]
HTML
<div id="gallery">
<div class="preview">
<img class="previewImg" src="http://cdn.shopify.com/s/files/1/0176/5914/files/Kaylee_Radzyminski.jpg?7297" alt="" title="" />
<div class="previewText"></div>
</div>
<div class="thumbnails">
<a href="javascript: void(0);">
<img src="http://cdn.shopify.com/s/files/1/0176/5914/files/Kaylee_Radzyminski.jpg?7297" alt="" title="Image 1" />
</a>
<a href="javascript: void(0);">
<img src="http://cdn.shopify.com/s/files/1/0176/5914/files/Mason_Hunter_Thornal.jpg?7297" alt="" title="Image 2" />
</a>
<a href="javascript: void(0);">
<img src="http://cdn.shopify.com/s/files/1/0176/5914/files/Joseph_Nunez_4afb23ac-d71e-42a0-9366-ac78d65deaf4.jpg?7297" alt="" title="Image 3" />
</a>
</div>
</div>
CSS
#gallery {
overflow: hidden;
}
#gallery .preview {
float: left;
position: relative;
}
#gallery .previewImg {}
#gallery .previewText {
position: absolute;
right: 0;
bottom: 0;
left: 0;
height: 100px;
background: rgba(0,0,0,0.7);
color: #fff;
font: normal 12px arial;
padding: 10px;
}
#gallery .thumbnails {
float: left;
width:100px;
}
#gallery .thumbnails a, #gallery .thumbnails img {
display: block;
}
#gallery .thumbnails a img {
width: 100%;
opacity: .5; /* css standard */
filter: alpha(opacity=50); /* internet explorer */
}
#gallery .thumbnails a:hover img {
opacity: 1; /* css standard */
filter: alpha(opacity=100); /* internet explorer */
}
JS
$(function(){
var gallery = $("#gallery"),
thumbnails = gallery.find(".thumbnails a"),
previewImg = gallery.find(".previewImg"),
previewText = gallery.find(".previewText");
thumbnails.on("click", function(e){
var thumbImg = $(this).find("img");
previewImg.attr("src", thumbImg[0].src);
previewText.html(thumbImg[0].title);
});
});
I'd call the onclick from the image itself instead of adding the onclick via JS to the image.
You're doubling your work.
Where do you want the text to be displayed?
If it has to be displayed on top of the image, you'll have to make the image a background-image of a div or so.
If the text has to be above/under the image, place a span above/under the image and give it an ID.
Working with a span
JS:
function showBig(srcBig, title) {
var mainImg = document.getElementById('MainImg');
var mainText = document.getElementById('MainText');
mainImg.src = srcBig;
mainImg.title = title;
mainText.innerHTML = title;
}
HTML:
<div id="main">
<span id="MainText">Title will come here</span>
<img src="Default Img" alt="Big img's will come here" />
</div>
<img src="URL of thumbnail (e.g. smaller version)" alt="" onClick="showBig('URL of big version', 'Title')" />
Working with BG-image
JS:
function showBig(srcBig, title) {
var mainDiv = document.getElementById('MainDiv');
MainDiv.style.backgroundImage = srcBig;
MainDiv.innerHTML = title;
}
HTML:
<div id="MainDiv">
</div>
<img src="URL of thumbnail (e.g. smaller version)" alt="" onClick="showBig('URL of big version', 'Title')" />
By the way, you can ofc still add the onClicks via JS:
document.getElementById("yourImg").onclick = showBig('URL of Big', 'Title');
By the way, Don't use the same img for the thumbnails.
You'll probably use some big images which takes longer to load and then display it much smaller via CSS.
Make a smaller version (e.g. 100x100px or whatever size the thumbs should be) and only load the bigger version when the onClick is called.
Also, you better use a CSS-class like .thumbs to style the thumbs.
Otherwise you'll have to add a new ID to the list in your CSS file everytime you add a new image.
JSFiddle

Categories

Resources