I have a 8 div at present and it may increase or decrease in count.Each of these div contain on clicking which it displays content relate to it.At a fixed with of 1024px and above it is working fine.But problem is all these div are responsive,at lower resolution the hidden div that is to be displayed are misaligned. Can any one help me in the same ?
This is the html core that i have wrote:-
<div class="client-details fl_left" style="display: none;"
id="citiCab2">
<span class="pointer" style="left: 73px;"></span> <a
class="close-button" href=""></a>
<div class="client-container fl_left">
<a href="http://citicabsinc.com/" target="_blank"><img
src="images/citicabs-big.png"></a>
</div>
<div class="client-container fl_right">
<h1>Citi Cabs</h1>
<p>The client is a progressive firm, providing eminent car rental
services to all kinds for travel requirements. It caters transport
and communication to its customers all over India.</p>
<p class="title">Client Requirement </p>
<p>The client wanted to come up with a website portal, that can be
navigated with ease by the visitor who is looking for the car
service within Bangalore and anywhere in India.</p>
<p class="title">Challenge</p>
<p>We the Maganiva Solutions Team had to predominantly understand
website workflow making it intuitive for the user to use it with
ease keeping in mind the visitor's page. </p>
<p class="title">What Maganiva Solutions delivered </p>
<p>Maganiva did a complete market study to get insights and came up
with a comprehensive model, wherein we not only designed the user
friendly website but also provided back-end support to the client
in Branding its online presence through SEO.</p>
</div>
</div>
Java script for the same.Also help to reduce the size of the code, as you can see i have simply repeated the same code again and again with only difference in the id to be called on mouse click to a particular div.
jQuery(function() {
$('#citiCab1').click(function() {
$(".client-details").addClass('display-none');
$('#citiCab2').attr('style', function(i, style) {
jQuery(this).removeClass('display-none');
return style.replace(/display[^;]+;?/g, '');
});
$("#citiCab2").addClass('display');
});
$('#primus1').click(function() {
$(".client-details").addClass('display-none');
$('#primus2').attr('style', function(i, style) {
jQuery(this).removeClass('display-none');
return style.replace(/display[^;]+;?/g, '');
});
$("#primus2").addClass('display');
});
$('#MantriEden1').click(function() {
$(".client-details").addClass('display-none');
$('#MantriEden2').attr('style', function(i, style) {
jQuery(this).removeClass('display-none');
return style.replace(/display[^;]+;?/g, '');
});
$("#MantriEden2").addClass('display');
});
$('#DilDaruDosti1').click(function() {
$(".client-details").addClass('display-none');
$('#DilDaruDosti2').attr('style', function(i, style) {
jQuery(this).removeClass('display-none');
return style.replace(/display[^;]+;?/g, '');
});
$("#DilDaruDosti2").addClass('display');
});
$('#chai1').click(function() {
$(".client-details").addClass('display-none');
$('#chai2').attr('style', function(i, style) {
jQuery(this).removeClass('display-none');
return style.replace(/display[^;]+;?/g, '');
});
$("#chai2").addClass('display');
});
$('#mbnt1').click(function() {
$(".client-details").addClass('display-none');
$('#mbnt2').attr('style', function(i, style) {
jQuery(this).removeClass('display-none');
return style.replace(/display[^;]+;?/g, '');
});
$("#mbnt2").addClass('display');
});
$('#act1').click(function() {
$(".client-details").addClass('display-none');
$('#act2').attr('style', function(i, style) {
jQuery(this).removeClass('display-none');
return style.replace(/display[^;]+;?/g, '');
});
$("#act2").addClass('display');
});
$('#mathru1').click(function() {
$(".client-details").addClass('display-none');
$('#mathru2').attr('style', function(i, style) {
jQuery(this).removeClass('display-none');
return style.replace(/display[^;]+;?/g, '');
});
$("#mathru2").addClass('display');
});
});
Hope this what you are looking for, try the below html. Hope it helps you!!!
HTML:
<p><strong>Head1</strong></p>
<div class="desc" id="desc1" style="display: none;">
<h2>Description 1</h2>
<p>Content</p>
<p><a class="close" href="JavaScript:toggleMe('desc1');">Close</a></p>
</div>
<p><strong>Head2</strong></p>
<div class="desc" id="desc2" style="display: none;">
<h2>Description 2</h2>
<p>Content</p>
<p><a class="close" href="JavaScript:toggleMe('desc2');">Close</a></p>
</div>
CSS:
.close{
text-align:right;
display:block;
padding:10px;
}
.desc{
background:#dedede;
padding:10px;
}
Script:
<script>
function toggleMe(a) {
var e = document.getElementById(a);
if (!e) return true;
if (e.style.display == "none") {
e.style.display = "block"
} else {
e.style.display = "none"
}
}
</script>
Fiddle Demo
Related
I'm currently building a script to create a slider and stumbled upon an error I can't seem to solve. Basically I trying to get the width of a container and multiply it base on the number of slides inside.
Here is a snippet a of the code I'm working on. Whenever I try to use .width in order to fetch the width of a container it returns undefined on the console. I tried looking back and forth on my code but I can't seem to pinpoint the issue.
_setSliderWidth() {
this.sliderBanner = this.$el.find('.slider-banner');
this.sliderBannerWidth = this.sliderBanner.width();
console.log(this.sliderBannerWidth);
this.slides.width(this.sliderBannerWidth);
this.slidesContainer.width(this.sliderBanner.width() * this.slideCount);
}
-- -- -- -- --
'use strict';
(function($) {
/**
* Base Image Slider class
*/
class ImageSlider {
constructor(el) {
this.$el = $(el);
this._dom();
this.slideCount = this.slides.length;
this.currentSlide = 0;
this.arrows = {
prev: this.$el.find('.arrow.-prev'),
next: this.$el.find('.arrow.-next')
};
// image formatting and detection
this.$el.find('img').each(function(e, el) {
let $img = $(el);
if ($img.height() > $img.width())
$img.addClass('-portrait');
});
this._setSliderWidth();
}
_dom() {
this.slides = this.$el.find('.slides');
this.slidesContainer = this.$el.find('.slider-items');
}
init() {
this._bind();
this._evaluatePosition();
}
_bind() {
this.arrows.next.on('click', this._nextSlide.bind(this));
this.arrows.prev.on('click', this._prevSlide.bind(this));
}
_nextSlide() {
this.currentSlide++;
this._moveSlide();
}
_prevSlide() {
this.currentSlide--;
this._moveSlide();
}
_setSliderWidth() {
this.sliderBanner = this.$el.find('.slider-banner');
this.sliderBannerWidth = this.sliderBanner.width();
console.log(this.sliderBannerWidth);
this.slides.width(this.sliderBannerWidth);
this.slidesContainer.width(this.sliderBanner.width() * this.slideCount);
}
_moveSlide() {
// set the min and max range
if (this.currentSlide < 0) this.currentSlide = 0;
if (this.currentSlide > this.slideCount - 1) this.currentSlide = this.slideCount - 1;
this._evaluatePosition();
this._move();
}
_move() {
let position = this.currentSlide * -100;
this.slidesContainer.css({
transform: 'translate(' + position + '%, 0)'
});
}
_evaluatePosition() {
this.arrows.prev.toggleClass('-hide', (this.currentSlide === 0));
this.arrows.next.toggleClass('-hide', (this.currentSlide === this.slideCount - 1));
}
}
$(document).ready(function() {
//--------------------------------------------------
// Image Slider
let $imageSliders = $('.image-slider');
$imageSliders.each(function(e, el) {
let imageSlider = new ImageSlider(el);
imageSlider.init();
});
//--------------------------------------------------
// Slider Banner
let $bannerSliders = $('.slider-banner');
$bannerSliders.each(function(e, el) {
let bannerSlider = new ImageSlider(el);
bannerSlider.init();
});
});
})(jQuery);
HTML
<div class="slider-banner -alternate">
<span href="#" class="arrow -prev -hide"></span>
<span href="#" class="arrow -next"></span>
<div class="slider-items">
<div class="slides">
<div class="image" style="background-image:url(/iom/sites/default/files/2018-07/partnerships-2_0.jpg)">
<div class="banner-detail">
<div class="article-detail">
<div class="timestamp">
page
</div>
<h2 class="title">
Migrant Integration
</h2>
<div class="mini-caption">
IOM supports policies and strategies that promote the social, economic and cultural inclusion of migrants within existing legal frameworks in countries of destination.
</div>
More Details
</div>
</div>
</div>
</div>
<div class="slides">
<div class="image" style="background-image:url(/iom/sites/default/files/2018-07/definitional-issues_1.jpg)">
<div class="banner-detail">
<div class="article-detail">
<div class="timestamp">
page
</div>
<h2 class="title">
Forum on Migration, Trade and the Global Economy
</h2>
<div class="mini-caption">
IOM, together with partners ICTSD and Fundanción Foro del Sur will host the Forum on Migration, Trade & the Global Economy in Buenos Aires on 14 December.
</div>
More Details
</div>
</div>
</div>
</div>
<div class="slides">
<div class="image" style="background-image:url(/iom/sites/default/files/2018-07/identity-management_0.jpg)">
<div class="banner-detail">
<div class="article-detail">
<div class="timestamp">
page
</div>
<h2 class="title">
Comparative Research on the Assisted Voluntary Return and Reintegration of Migrants
</h2>
<div class="mini-caption">
Assisted Voluntary Return and Reintegration (AVRR) is an indispensable part of a comprehensive approach to migration management aiming at orderly and humane return and reintegration of migrants.
</div>
More Details
</div>
</div>
</div>
</div>
</div>
</div>
It seems from your screenshots and code that the this. sliderBanner object does NOT return a DOM object and thus the .width() would be undefined.
To resolve you can:
1) Retrieve the DOM object through a weird method of this.sliderBanner.prevObject. More information in this thread: What is prevObject and why is my selector returning that?
The main problem is that the .find from the $el object can't doesn't have the slider banner object within it's DOM, so...
2) Try using this.sliderBanner = $(".slider banner") to select the banner from the document object instead
I have chosen this way of doing it so i can just drop a hand full of images in to a folder and that's it, I have tried many ways but nothing works, my latest attempt is using
$(".image-container").find("img[src=" + Img + "]").next('img').attr('src');
but still no go.
This is what i have come up with so far, any help would be great, Thank's
<div id="removed-container" style="height: 600px;">
<div id="removed" style="height: 600px;">
<div style="float: left; width: 200px;">
<h1> <span>The Gallery</span> </h1>
<ul id="nav">
<li>Gallery
<ul>
<li>2015</li>
<li>2015</li>
<li>2015</li>
<li>2015</li>
<li>2015</li>
</ul>
</li>
<li>Back to home</li>
</ul>
</div>
<div class="image-container"></div>
<script type="text/javascript"> $(document).ready(function () {
$("a").click(function () {
var dir_path=$(this).data("albumid");
LoadGallery(dir_path);
return false;
});
});
function LoadGallery(dir_path) {
$.ajax({
url: dir_path,
success: function(data) {
$(".image-container").empty();
$(data).find("a:contains(.jpg), a:contains(.png), a:contains(.jpeg)").each(function() {
this.href.replace(window.location.host,"").replace("http:///",""); file=dir_path+$(this).text();
$(".image-container").append($("<a href='java<!-- no -->script:;' class='thumb' data-src='"+file+"'><img src='"+file+"' title='Click to enlarge' alt='#'/></a>"));
if ($(".image-container").children("a").length == 30) {
return false;
}
});
$(".thumb").bind('click', function() {
var Popup="<div class='bg'></div>"+"<div class='wrapper'><img src='<img src=''/>"+"<label href='javascript:;' class='prev-image'>«</label><label href='javascript:;' class='next-image'>»</label><a href='java<!-- no -->script:;' class='close' title='Close'>Close</a>";
Img = $(this).attr("data-src"),
$("body").prepend(Popup);
$(".bg").height($(window).height()*4);
$(".wrapper img").attr("src", Img);
$(".prev-image").bind ('click',function() {
alert("Prev")
})
$(".next-image").bind ('click',function() {
next = $(".image-container").find("img[src=" + Img + "]").next('img').attr('src');
//alert(next)
})
$(".close").bind ('click',function() {
$(this).siblings("img").attr("src", "")
.closest(".wrapper").remove();
$(".bg").remove();
});
});
}
});
} </script>
<div class="clear"></div>
The problem is in the usage of next().
From documentation - Get the immediately following sibling of each element in the set of matched elements.
And as in your case, img are not siblings, hence, there are no matched set of elements.
If your hierarchy is strict and is not going to change, then you can do something like following
/* Find image - go its parent - go to next anchor - get the image - get the source */
$(".image-container").find("img[src='" + Img + "']").parent().next('a').find("img").attr('src');
Else you can iterate over the images.
For reference - http://plnkr.co/edit/onUeWl8mPqVhtaHf37xp?p=preview
Please try this:
$('#id').next().find('img').attr("src");
I have eight cards with two parameters on each of them. The first parameter is year (2011, 2012, 2013, 2014), the second is category (studio, house, personal, commercial). It looks like this:
Studio 2011
House 2012
Commercial 2013
Personal 2012
Studio 2014
Commercial 2011
House 2014
Personal 2013
I need to sort them out, making needed cards bright, and not needed faded. By default all of them are bright. HTML:
<div class="card card-studio card-2011 card-bright">Studio 2011</div>
<div class="card card-house card-2012 card-bright">House 2012</div>
<div class="card card-commercial card-2013 card-bright">Commercial 2013</div>
<div class="card card-personal card-2012 card-bright">Personal 2012</div>
<div class="card card-studio card-2014 card-bright">Studio 2014</div>
<div class="card card-commercial card-2011 card-bright">Commercial 2011</div>
<div class="card card-house card-2014 card-bright">House 2014 </div>
<div class="card card-personal card-2013 card-bright">Personal 2013</div>
I add buttons with years:
2011
2012
2013
2014
When user clicks a year button, we take cards with needed year class and remove their "bright/faded" classes just in case. Then we add "bright" class to these cards. Then we take all the cards that do not have needed year and add them "faded" class (also removing previous classes just in case). And we also make the button underlined, and its siblings not underlined. It all looks like this:
$(".button").on("click", function(event){
event.preventDefault();
if($(this).hasClass("button-2011")){
$(".card-2011").removeClass("card-bright card-faded").addClass("card-bright");
$(".card").not(".card-2011").removeClass("card-bright card-faded").addClass("card-faded");
$(this).siblings().removeClass("button-active").end().addClass("button-active");
}
JSfiddle: https://jsfiddle.net/6vLzyowc/
Now it all seems simple, but trouble comes up when I try to add the second sorting condition, category.
On the one hand, I certainly need to do the same thing, as in the first case, i. e. make needed category bright, not needed faded:
if($(this).hasClass("button-house")){
$(".card-house").removeClass("card-bright card-faded").addClass("card-bright");
$(".card").not(".card-house").removeClass("card-bright card-faded").addClass("card-faded");
}
But it will make "bright" all cards with the needed category, and I also have the previous year sorting results. It seems that I need to sort them out first. So, I take the first year sorting results (i. e. "bright" cards) and make ones without needed category "faded":
if($(this).hasClass("button-house")){
$(".card-bright").not("card-house").addClass("card-faded");
}
It helps a little, but I still don't know how I can add the remaining cards with needed category now, so that both conditions are satisfied. So, how can I combine sorting previous sorting results and sorting all the items?
Fiddle with all the buttons: https://jsfiddle.net/hm1emr8p/
I think your approach is a bit over-complicated. The following works for any number of filters. The trick is to keep state of what is selected, and on any change just re-apply this state to the card-elements.
(function () {
var active = [];
$('.filter').each(function (idx, el) {
var $el = $(el);
active.push('');
$el.on('click', '.button', function () {
var $this = $(this);
active[idx] = $this.data('toggle');
$el.find('.button').removeClass('button-active');
$this.addClass('button-active');
update();
});
});
function update()
{
var a = active.join('');
if (a.length === 0) {
$('.card').removeClass('card-faded');
}
else {
$('.card').addClass('card-faded').filter(active.join('')).removeClass('card-faded');
}
}
})();
a {
text-decoration: none;
color: black;
}
.buttons {
margin-top: 40px;
}
.time {
margin-bottom: 20px;
}
.card-faded {
opacity: 0.3;
}
.button-active {
text-decoration: underline;
}
<script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
<div class="card card-2011 card-studio">Studio 2011</div>
<div class="card card-2012 card-house">House 2012</div>
<div class="card card-2013 card-commercial">Commercial 2013</div>
<div class="card card-2012 card-personal">Personal 2012</div>
<div class="card card-2014 card-studio">Studio 2014</div>
<div class="card card-2011 card-commercial">Commercial 2011</div>
<div class="card card-2014 card-house">House 2014 </div>
<div class="card card-2013 card-personal">Personal 2013</div>
<div class="buttons">
<div class="filter time">
<a class="button button-2011" data-toggle=".card-2011">2011</a>
<a class="button button-2012" data-toggle=".card-2012">2012</a>
<a class="button button-2013" data-toggle=".card-2013">2013</a>
<a class="button button-2014" data-toggle=".card-2014">2014</a>
<a class="button button-all button-active" data-toggle="">All time</a>
</div>
<div class="filter category">
<a class="button button-studio" data-toggle=".card-studio">Studio</a>
<a class="button button-house" data-toggle=".card-house">House</a>
<a class="button button-commercial" data-toggle=".card-commercial">Commercial</a>
<a class="button button-personal" data-toggle=".card-personal">Personal</a>
<a class="button button-all button-active" data-toggle="">All</a>
</div>
</div>
I suggest saving the selected category and the selected timespan in variables:
var lastCategory = '';
var lastYear = '';
In your case you can use data- attributes to store information like this:
2011
and:
Studio
And perform actions based on the value of the data element in your click handler:
$(".category > .button").on("click", function(event){
event.preventDefault();
var tmpCat = $(this).data('cat');
lastCategory = tmpCat;
$(".card").removeClass("card-faded");
if (tmpCat == 'all') {
if (lastYear == 'alltime') {
$(".card").addClass("card-faded");
} else {
$(".card-"+lastYear).addClass("card-faded");
}
} else {
if (lastYear == 'alltime') {
$(".card-" + tmpCat).addClass("card-faded");
} else {
$(".card-" + tmpCat + ".card-"+lastYear).addClass("card-faded");
}
}
$(this).siblings()
.removeClass("button-active")
.end()
.addClass("button-active");
});
$(".time > .button").on("click", function(event){
event.preventDefault();
var tmpYear = $(this).data('year');
lastYear = tmpYear;
$(".card").removeClass("card-faded");
if (tmpYear == 'alltime') {
if (lastCategory == 'all') {
$(".card").addClass("card-faded");
} else {
$(".card-" + lastCategory).addClass("card-faded");
}
} else {
if (lastCategory == 'all') {
$(".card-" + tmpYear).addClass("card-faded");
} else {
$(".card-" + lastCategory + ".card-"+tmpYear).addClass("card-faded");
}
}
$(this).siblings()
.removeClass("button-active")
.end()
.addClass("button-active");
});
There a zillion ways that lead to rome, this is not ideal, but try to avoid if (1) then, if (2) then, if (3) then, etc.... code. I forked your fiddle and made a working demo.
I had a look out on the interwebs for a jQuery image gallery and couldn't find one that suited what I wanted to do. So I, ended up creating one myself and am trying to figure out how to get the prev and next buttons to work.
<div class="gallery portrait">
<nav>
<div class="close"></div>
<div class="prev"></div>
<div class="next"></div>
</nav>
<div class="cover">
<img src="image.jpg">
</div>
<ul class="thumbs">
<li class="thumb">
<img src="image.jpg">
</li>
...
</ul>
</div>
I'm also using a bit of jQuery to add a class of .full to the .thumb a element, which makes the thumbnails go fullscreen.
$( ".thumb a" ).click(function() {
$( this ).toggleClass( "full" );
$( "nav" ).addClass( "show" );
});
Now I can't work out this next bit, I need a way when the .prev or .next buttons are clicked for it to remove the class of .full from the current element and add it to the next or previous .thumb a element, depending on which was clicked.
I've got a demo setup here: http://codepen.io/realph/pen/hjvBG
Any help is appreciated, thanks in advance!
P.S. If this turns out well, I plan on releasing it for free. I guess you can't have too many jQuery image galleries, eh?
You can use $.next() and $.prev():
$(".prev").click(function () {
var current = $('.full');
current.prev('.thumb').addClass('full');
current.removeClass('full');
return false; // stop propagation; prevents image click event
});
$(".next").click(function () {
var current = $('.full');
current.next('.thumb').addClass('full');
current.removeClass('full');
return false; // stop propagation; prevents image click event
});
I suggest the following additions to your code to handle wrapping around with your next and previous links:
$(".next").click(function (event) {
navigate("next");
return false;
});
$(".prev").click(function (event) {
navigate("prev");
return false;
});
function navigate(operation) {
var $thumbs = $(".thumb"),
$full = $thumbs.find("a.full").closest(".thumb"),
$next;
$thumbs.find('a').removeClass('full');
if (operation == 'prev' && $full.is($thumbs.first()))
$next = $thumbs.last();
else if (operation == 'next' && $full.is($thumbs.last()))
$next = $thumbs.first();
else
$next = $full[operation]();
$next.find('a').click();
}
Here is a forked CodePen.
Something like this will get you started, but what you're wanting to do takes a little time to get just right.
<script type="text/javascript">
var imgSrcs = ['/imgs/this.jpg', '/imgs/will.jpg', '/imgs/work.jpg', '/imgs/just.jpg', '/imgs/fine.jpg'];//img url loaded into an array
var btnPrev = document.getElementById('prev'),
btnNext = document.getElementById('next'),
cover = document.getElementById('cover'),
thumb = document.getElementById('thumb'),
currImgIx = 0;
btnPrev.onclick = function () {
if (currImgIx === 0) { return; };
currImgIx--;
cover.src = imgSrcs[currImg];
thumb.src = imgSrcs[currImgIx];
};
btnNext.onclick = function () {
if (currImgIx === imgSrcs.length - 1) { return; };
currImgIx++;
cover.src = imgSrcs[currImgIx];
thumb.src = imgSrcs[currImgIx];
};
</script>
<div class="gallery portrait">
<nav>
<div class="close">X</div>
<div id="prev" class="prev">Prev</div>
<div id="next" class="next">Next</div>
</nav>
<div class="cover">
<img id="cover" src="image.jpg">
</div>
<ul class="thumbs">
<li class="thumb">
<img id="thumb" src="image.jpg">
</li>
...
</ul>
</div>
An update to before, here's what I'm dealing with:
<body>
<div class="header"> <img class="imgLogo" src="img/vegtablelogo.jpg"> </div>
<div id="thumbsContainer">
<div class="thumb" id="carrotThumb"> <img id="showCarrot" class="imgThumb" src="img/carot.jpg" onClick=setupVeg("showCarrot", "carrotBig") /> </div>
<div class="hidden" id="carrotBig"> <img class="imgBig" src="img/carot.jpg" /> </div>
<div class="thumb" id="brocThumb"> <img id="showBroc" class="imgThumb" src="img/brocoli.jpg" onClick=setupVeg("showBroc", "brocBig") /> </div>
<div class="hidden" id="brocBig"> <img class="imgBig" src="img/brocoli.jpg" /> </div>
</div>
<!-- end thumbs container -->
<script>
var active = "";
function setupVeg(thumbVeg, hiddenVeg) {
$("#" + thumbVeg).click(function() {
if (active != hiddenVeg) {
$("div.hidden").hide("fast");
$("#" + hiddenVeg).show("fast", function() {});
active = hiddenVeg;
}
else {
$("div.hidden").hide("fast");
active="";
}
});
}
$("div.hidden").click(function () {
$("div.hidden").hide("fast");
isAnyBig=false;
});
</script>
</body>
This code is not working unfortunately. I have borrowed from suggested solution below.
Would be nice if it did work!
Any suggestions, most welcome.
I don't think you need any of the flags or the if conditions really. I think your logic is:
toggle carrotBig whenever showCarrot
is clicked.
hide div.hidden whenever showCarrot is clicked.
So all you need is:
$("#showCarrot").click(function () {
$("#carrotBig").toggle("fast");
$("#div.hidden").hide();
});
.toggle will handle one of your flags (isCarrotBig) and .hide() won't do anything if div.hidden is already hidden, so that takes care of your isAnyBig flag.
Now.. let's make that work with broc as well...
function setupVegetable(showId, toggleId) {
$("#" + showId).click(function () {
$("#" + toggleId).toggle("fast");
$("#div.hidden").hide();
});
}
setupVegetable("showCarrot", "carrotBig");
setupVegetable("showBroc", "brocBig");
If you're interested, you can refactor it FURTHER so you don't need to supply the IDs for each of the vegetables. I'll need to see your HTML markup though.
Ok I'll post a new answer in response to the edit.
Points worth noting:
Removed divs surrounding the imgs - they are unnecessary and complicate the relationship between the thumnnails and the large images.
Removed onclick attribute from within HTML - you will be attaching the event handlers in the JS so this is not needed.
Since the relationship between the thumbnails and the large images is quite obvious (the large images is just the next element) you don't need IDs to identify ANY of them. All you need is a class on the thumbnails.
Since we're not using IDs, only classes, you can add as many vegetables as you want without touching the JS
Your code modified:
<body>
<div class="header"> <img class="imgLogo" src="img/vegtablelogo.jpg"> </div>
<div id="thumbsContainer">
<img class="imgThumb" src="img/carot.jpg" />
<img class="imgBig hidden" src="img/carot.jpg" />
<img class="imgThumb" src="img/brocoli.jpg" />
<img class="imgBig hidden" src="img/brocoli.jpg" />
</div>
<!-- end thumbs container -->
<script>
$("#thumbsContainer .imgThumb").click(function () {
var thisImgBig = $(this).next();
// Hide all imgBigs, except for this one
$("#thumbsContainer .imgBig").not(thisImgBig[0]).hide();
// Toggle this imgBig
thisImgBig.toggle();
});
$("#thumbsContainer .imgBig").click(function () {
// Hide this imgBig
$(this).hide();
});
</script>
</body>
create a function and reuse it....something like:
/**
* document here....
*/
var toggleElements = function() {
// your code here
}
and then
$("#whatever").click(toggleElements);
Personally I would suggest creating a simple jQuery plugin. Something like so:
(function($){
$.fn.big = function(options) {
var defaults = {
target: '#carrotBig',
};
var options = $.extend(defaults, options);
return this.each(function() {
$(this).click(function () {
isBrocBig=false;
if (isCarrotBig == false && isAnyBig == false) {
$(options.target).show("fast", function() {});
isCarrotBig=true;
isAnyBig=true;
}
else if (isCarrotBig == true) {
$(options.target).hide("fast");
isCarrotBig=false;
isAnyBig=false;
}
else if (isCarrotBig == false && isAnyBig == true) {
$("div.hidden").hide("fast");
$(options.target).show("fast", function() {});
isCarrotBig=true;
}
else {
$("div.hidden").hide("fast");
isCarrotBig=false;
isAnyBig=false;
}
});
});
};
})(jQuery);
Then you just call it with something like so:
$("#showCarrot").big({target: '#carrotBig'})
Your next step should be to investigate whether you can get rid of the global variables or not.
Ok I have found a neat(ish) sollution, dependent on each hidden DIV being the .next() one. If it isn't it won't work but should be fine generally though. Hacked!
<div class="header"> <img class="imgLogo" src="img/vegtablelogo.jpg"> </div>
<div id="thumbsContainer">
<div class="thumb" id="carrotThumb"> <img id="showCarrot" class="imgThumb" src="img/carot.jpg" /> </div>
<div class="hidden" id="carrotBig"> <img class="imgBig" src="img/carot.jpg" /> </div>
<div class="thumb" id="brocThumb"> <img id="showBroc" class="imgThumb" src="img/brocoli.jpg" /> </div>
<div class="hidden" id="brocBig"> <img class="imgBig" src="img/brocoli.jpg" /> </div>
</div>
<!-- end thumbs container -->
<script>
var active = "";
$("div.thumb").click(function() {
var thumbVeg = $(this).attr("id");
var hiddenVeg = $(this).next().attr("id");
setupVeg(thumbVeg, hiddenVeg);
});
function setupVeg(thumbVeg, hiddenVeg) {
if (active != hiddenVeg) {
$("div.hidden").hide("fast");
$("#" + hiddenVeg).show("fast", function() {});
active = hiddenVeg;
}
else {
$("div.hidden").hide("fast");
active="";
}
}
$("div.hidden").click(function () {
$("div.hidden").hide("fast");
});
</script>