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
Related
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
I have an HTML page with an image(wanna use as a button) and some several images that I set to be invisible by CSS visibility: hidden. I want to make when i click this 'image 'w-click.png'' another several image appear.
so, tag to some other images. In my case, I want the click 'w-click.png' to invoke a JavaScript to display the images.
i found one click one image appearing, but i want one click several images appearing....
edit : this is my code
<img src="IMAGE/w-click.png" style="z-index:200; margin-left:6680px; position:relative; width:700px; margin-top:-100px; padding:0; position:absolute; " />
<div class="invisible-livingroom">
<img src="IMAGE/w-clock.png" style="position:absolute; margin-left:1200px; filter:brightness(1.3);visibility:hidden; " />
<img src="IMAGE/w-stand.png" style="position:absolute; margin-left:1830px; margin-top:120px;filter:brightness(1.2); height:800px; z-index:5; visibility:hidden;"/>
<img src="IMAGE/w-cushion.png" style="position:absolute; margin-left:1450px; margin-top:270px; transform:rotate(2deg); visibility:hidden;"/>
<img src="IMAGE/w-light.png" style="position:absolute; margin-left:1310px; width:900px; margin-top:-130px; filter:brightness(0.95); visibility:hidden;" />
<img src="IMAGE/w-livingroom-table.png" style="position:absolute; margin-left:1310px; width:900px; margin-top:240px; filter:brightness(1.6); visibility:hidden;"/>
<img src="IMAGE/w-frame2.png" style="position:absolute; width:300px; margin-left:1500px; margin-top:120px; visibility:hidden;"/>
</div>
edit: i added this javascript code and add id="myImageId' to every images but it makes only one image appears
function showImage() {
var img = document.getElementById('myImageId');
img.style.visibility = 'visible';
}
var imagesRoot = document.getElementsByClassName("invisible-livingroom");
var images = imagesRoot[0].getElementsByTagName("img");
for (var i = 0; i < images.length; i++) {
images[i].style.visibility = "visible";
}
in jQuery it is as simple as
$(".invisible-livingroom img").css("visibility", "hidden")
Add class to all images say "hid_img"
<div class="invisible-livingroom">
<img class="hid_img" src="IMAGE/w-clock.png" style="position:absolute; margin-left:1200px; filter:brightness(1.3);visibility:hidden; " />
<img class="hid_img" src="IMAGE/w-stand.png" style="position:absolute; margin-left:1830px; margin-top:120px;filter:brightness(1.2); height:800px; z-index:5; visibility:hidden;"/>
</div>
Then you can use following script
var x = document.getElementsByClassName("hid_img");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.visibility = "visible";
}
Alternative, rather than hiding all your images, you can hide the entire div block as invisible and then display it on click.
<div id="lr" class="invisible-livingroom" style="visibility:hidden;"></div>
Then you can set its visibility as
document.getElementsById("invisible-livingroom").style.visibility = 'visible';
I will recommend you to give an id for triggering element, separating/moving from inline css to separate css file and there will be so many ways to work with javascript.
Please review this one
//declaring variables
var trigger = document.getElementById("trigger");
trigger.addEventListener('click', function(e) {
var c = document.getElementsByClassName("invisible-livingroom")[0] //only try to get first array. elements could have same class name
c.style.display = 'block';
})
/*set default none*/
.invisible-livingroom {
display: none;
}
/*for convenient only*/
img {
height: 50px;
width: 50px;
background-color:blue;
}
<img id="trigger" src="IMAGE/w-click.png" />
<div class="invisible-livingroom">
<img src="#"/>
<img src="#"/>
<img src="#"/>
<img src="#"/>
<img src="#"/>
</div>
Please visit this one:
w3schools
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();
});
I've got a bunch of images, on click I want the images to turn white emulating some kind of fade effect. So you click it and for 1 second it fades from the original image to just white. I also need it to turn back to the original image when the user clicks something else.
Is this possible with JavaScript? - If so what should I be looking at (I'm really bad with graphics).
I've had a go at trying this with opacity but I don't want the background to be visible behind the image
Psuedo-element Solution
You could use a wrapper with a pseudo-element to overlay what you're looking for -- and the animations are handled by a toggled CSS class (which is ideal for performance).
CodePen Demonstration
HTML
<div class="whiteclicker">
<img src="http://lorempixel.com/400/200" alt=""/>
</div>
SCSS
#import "compass/css3/transition";
body { background: gainsboro; text-align: center; }
.whiteclicker {
display: inline-block;
position: relative;
&::after {
content: "";
display: block;
position: absolute;
top:0; left:0; right:0; bottom:0;
background: white;
opacity: 0;
#include transition(opacity 1s ease);
}
&.active::after {
opacity: 1;
}
}
JS
$('.whiteclicker').click(function(){
$(this).toggleClass('active');
});
To ameliorate the Spencer Wieczorek solution (the way two seems to be the best solution on my opinion) :
What about creating the white div on the fly (and fade it in and out) instead of put it in the html code ?
See the fiddle.
$("#myImage").click(function(){
$(this)
.parent().css({position:'relative'}).end()
.after($('<div>')
.hide()
.css({position:'absolute'
, top: $(this).position().top
, left: $(this).position().left
, width: $(this).width()
, height: $(this).height()
, background: '#FFF'
})
.fadeIn('fast')
.on({
click : function(e){
$(this).fadeOut('fast', function(){ $(this).remove();});
}
})
);
});
Then, you don't have anything to add to the html code or in the css styles, Jquery does everything.
#Spencer Wieczorek : I did my own answer, because I did not agree with your way of designing the css style (the fixed position is really not good, especially if the page is scrolled for example...). Mine is more ... standalone-y ;)
You might want to try having two images stacked on each other.
See this:
<script type="text/javascript">
var image1 = '<img class="images" src="Image 1" onClick="switch();" />';
var image2 = '<img class="images" src="Image 2" onClick="switch();" />';
var currentImage = 1;
function switch(){
if(currentImage==1){
currentImage++;
document.getElementById("image").innerHTML = image2;
}
if(currentImage==2){
currentImage--;
document.getElementById("image").innerHTML = image1;
}
}
</script>
<style>
.images{ position:fixed; top: 0; left: 0; }
</style>
<img class="images" src="Black image" />
<div id="image"><img class="images" src="Image 1" onClick="switch();" /></div>
For the fade I'm just gonna see how you could do it.
EDIT:
<script type="text/javascript">
var fadecount = 100;
function fade() {
document.getElementById("imageToFade").style.opacity = fadecount;
fadecount--;
if(fadecount==0){
clearTimeout(fade);
}
}
function start_fade(){
var fade = setTimeout(fade(), 10);
}
</script>
With Base 64 you can just have the binary version of the picture and then an all white picture and based on the .click you reassign the src to the white base64...
document.getElementById("img").src = "data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg=="
just change to the all white version after the click, technically js driven from click event, and doesn't involve two different elements existing just at different layers...
I have 3 images that I want to rotate when a button is clicked.
image1, image2, image3.
If the image is at image1, then when clicked it should show image2 (and so on, in order of image1, .., image3).
When I am at image3, it should then hide the image, i.e. don't display it.
I need some help with the javascript function to do this, I already have the code for the button click event.
I am passing the toggle() function the jquery object $('myImageID');
$(document).ready(
function()
{
$('#button1').click( function() { toggleSector( $('#sector1') ) } ;
}
);
function toggleSector(o)
{
// help!
}
<div id="sector1"></div>
<input type="button" id="button1" value="Sector 1" />
Update
I have to somehow find the name of the current background image set to the
<div> where my image is.
Is there a background property to get the image name currently being displayed?
You can get a background-image by accessing it from the .css(name) method:
$("#sector1").css("background-image");
Without managing your list of images in an array or some other fashion, you're going to have to check each background-image to know when it's time to hide your element. This isn't a great way of working, as it doesn't allow you to easily add a new image in the future if you like.
Perhaps something like the following:
function toggle(el) {
var whenToHide = "background3.jpg";
var currBackground = $(el).css("background-image");
/* ...code... */
if (currBackground == whenToHide) {
$(el).remove();
}
}
Do you have to use the background image?
If not, here's a little code sample for what I would do.
<html>
<head>
<style type="text/css">
#imageRotater { list-style-type:none; }
#imageRotater, .imageRotater li { margin:0px auto; padding: 0px; }
#imageRotater img { display:none; }
</style>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.1.min.js"></script>
<script type="text/javascript">
(function($) {
$.fn.rotate = function() {
return this.each(function() {
var list = $(this).is('ul') ? $(this) : $('ul', this);
list.find('img:eq(0)').show();
$('img', list).click(function() {
$(this).hide().closest('li').next().find('img').show();
});
});
};
})(jQuery);
$(document).ready(function() {
$("#imageRotater").rotate();
});
</script>
</head>
<body>
<div id="sector1">
<ul id="imageRotater">
<li><img src="image1.png" alt="" /></li>
<li><img src="image2.png" alt="" /></li>
<li><img src="image3.png" alt="" /></li>
</ul>
</div>
</body>
</html>
Here's a thing that works.
Each overlay is initially hidden with CSS. Each time your button is clicked, all the overlays are hidden, then one is revealed based on some data stored on the button. If the data reaches the max number overlays + 1, none are shown and the data is reset to 0.
Markup
<div id="container" style="background: yellow">
<div class="overlay" style="background: red"></div>
<div class="overlay" style="background: green"></div>
<div class="overlay" style="background: blue"></div>
</div>
Style
div{
width: 100px;
height: 100px;
}
.overlay{
position: absolute;
top: 0;
left: 0;
display: none;
}
#container{
position: relative;
}
Script
$(function() {
var b = $('#button1');
b.data('next', 0);
b.data('max', $('.overlay').size()+1 );
b.click( function( e ) {
var next = $(this).data('next');
var o = $('.overlay');
o.hide();
o.eq(next).show();
next = (next+1) % $(this).data('max');
$(this).data('next', next);
});
});
In response to Bendeway's answer above, you'll need to insert before
list.find('img:eq(0)').show();
the following line:
list.find('img').hide();
This will hide all the images before it starts rotating through them.