I am creating an album feature in which the user can select photos from a group of photos, then apply them to a folder. The issue is, I am having trouble selecting specific photos and applying certain attributes to them (mainly css style, I want a border around the image when selected).
Here is the html/jquery:
HTML
<div class="demo-gallery">
<ul id="lightgallery" class="list-unstyled grid">
<?php foreach ( $media_items as $item ): ?>
<li>
<img class="img-responsive" id="lazy" data-src="<?php echo $item->image_path_sd; ?>">
</li>
<?php endforeach; ?>
</ul>
</div>
Jquery
var picture = document.querySelectorAll('#lazy');
$(picture).each(function () {
$(document).on('click', /*???*/, function () {
if ($(/*???*/).data('clicked', true)) {
$(/*???*/).css("border", "none");
$(/*???*/).data('clicked', false);
} else {
$(/*???*/).css("border", "4px solid #00CE6F");
$(/*???*/).data('clicked', true);
console.log($(/*???*/).data());
}
});
});
My guess is I need to figure out what goes where all of the ??? comments are, however, I could be trying this in the wrong direciton.
When I console.log(picture), I get an array of every photo. When I console.log(picture[2]), it shows the third picture. This is what I want, but how am I to apply these attributes to each individual photo?
Overall: I want user to click on photos they want, applying a highlighted border around the photo to let them know it's currently selected.
As you are using jQuery, there's no need to use document functions, you can grab the list of items when you select something that can be applied to multiple items (like a class name).
The key here is with jQuery, .each(function(){ }) passes in the element itself, which you can access using this. using $(pictures).each() lets you access each individual element in that set.
So, rather than applying a single click listener on the document, you can place a click listener on each img itself.
To show the border, place the style in the css file as a class and use the $().toggleClass(/* class name */) function.
var pictures = $('.lazy');
$(pictures).each(function () {
// apply click listener to each image
$(this).on('click', function () {
// toggle the checked value
if ($(this).data('clicked') == true) {
$(this).data('clicked', false);
} else {
$(this).data('clicked', true);
}
// toggles the border
$(this).toggleClass('selected');
// display contents of all the items
$(pictures).each(function(index){
console.log('img #' + index + ': ' + $(this).data("clicked"))
})
});
});
.lazy {
padding: 10px;
display: inline;
background-color: red;
margin: 10px;
}
.selected {
border: 2px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Replace with PHP foreach -->
<img class="lazy" src="#">
<img class="lazy" src="#">
<img class="lazy" src="#">
<img class="lazy" src="#">
<img class="lazy" src="#">
<!-- Replace with PHP foreach -->
Simplified
The other answers reminded me that this whole block can be condensed to the following code:
$('.lazy').on('click',function(){
$(this).toggleClass('selected');
})
.lazy {
background-color: red;
padding: 10px;
box-sizing: border-box;
}
.selected {
border: 2px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="lazy" src="#">
<img class="lazy" src="#">
<img class="lazy" src="#">
<img class="lazy" src="#">
<img class="lazy" src="#">
when you submit, just use $('.lazy.selected') to grab all the selected items.
You cannot use an identical id selector for multiple tags on the same HTML document, instead, use ".lazy" class selector.
then you can do something like this.
css:
.selected-image{
border:1px solid #000;
}
jquery:
$(".lazy").click(function(){
const img = $(this)
if(img.hasClass("selected-image")){
img.removeClass("selected-image")
}
else{
$(this).addClass("selected-image")
}
})
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 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
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();
});
1) How to get an alert when I select 1_1.jpg, 1_2.jpg, 1_3.jpg or 2_1.jpg, 2_2.jpg, 2_3.jpg and the other ones arn't selected? (something like this *_1.jpg, *_2.jpg, *_3.jpg)
2) How to randomly position the order of the images (ex: first one: 2_1.jpg, second: 1_5, third:1_9 etc. so only the end of src (_.jpg) should differe)?
http://jsfiddle.net/alecstheone/br4bS/
HTML:
<img class="image" src="../img/Album1/1_1.jpg">
<img class="image" src="../img/Album1/1_2.jpg">
<img class="image" src="../img/Album1/1_3.jpg">
<img class="image" src="../img/Album1/1_4.jpg">
<img class="image" src="../img/Album1/1_5.jpg">
<img class="image" src="../img/Album1/1_6.jpg">
<img class="image" src="../img/Album1/1_7.jpg">
<img class="image" src="../img/Album1/1_8.jpg">
<img class="image" src="../img/Album1/1_9.jpg">
<img class="image" src="../img/Album1/1_10.jpg">
<img class="image" src="../img/Album1/2_1.jpg">
<img class="image" src="../img/Album1/2_2.jpg">
<img class="image" src="../img/Album1/2_3.jpg">
CSS:
.img {
height:30px;
width:30px;
background:blue;
margin-left:10px;
}
.selected {
-moz-box-shadow: 0 0 7px 4px blue;
-webkit-box-shadow: 0 0 7px 4px blue;
box-shadow: 0 0 7px 4px blue;
}
JQUERY:
$( ".image" ).click(function() {
if($(this).hasClass("selected"))
$(this).removeClass("selected");
else
$(this).addClass("selected");
});
1) How to get an alert when I select 1_1.jpg, 1_2.jpg, 1_3.jpg or 2_1.jpg, 2_2.jpg, 2_3.jpg and the other ones arn't selected? (something like this *_1.jpg, *_2.jpg, *_3.jpg)
Get your img elements in an array $("img"), and then condition on both the src and class attributes in this array.
2) How to randomly position the order of the images (ex: first one: 2_1.jpg, second: 1_5, third:1_9 etc. so only the end of src (_.jpg) should differe)?
Get your img elements in an array $("img"), shuffle that array, and then append the elements to a container. See here for an example.
1) For the selecting, it works like below. It'll give an alert on selecting image 1_1. I think you'll find it not too hard to work with the rest.
//If you select any image you get an alert.
$(document).ready(function() {
var selectedImgsArr = [];
$("img").click(function() {
//alert image name.
var src = $(this).attr('src');
if(src="../img/Album1/1_1.jpg") {
alert("1_1 selected");
}
});
});
2) You can basically have a function that randomises an array with the image names in them and shuffle it, to print it with JQuery then. Look here how to.
Good luck with it!
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.