Change the css of a div when a specific image is clicked - javascript

I have three images and depending on which image is clicked I want to change the css of a specific div. I just don't understand how to connect the click of an image to the div.
Below is a (bad) example of how I think it should work. I don't understand how this is accomplished without creating a function for each image/click.
$('.circle_hiw_cont img').click(
function() {
if(this == content_img_1.jpg) {
$("#content_1").css("display", "block");
$("#content_2").css("display", "none");
$("#content_3").css("display", "none");
} else {
}
}
);
HTML:
<img id="content_img_1" src="images/conent_img1.jpg"/>
<img id="content_img_2" src="images/conent_img2.jpg"/>
<img id="content_img_3" src="images/conent_img3.jpg"/>
<div id="content_1">This is div 1</div>
<div id="content_2">This is div 2</div>
<div id="content_3">This is div 3</div>
CSS:
#content_1{display:block;}
#content_2{display:none;}
#content_3{display:none;}

You can add classes to the elements and use the index and eq methods:
var $img = $('.img').on('click', function() {
$('.div').hide().eq( $img.index(this) ).show();
});
Note that as this solution is index-based, the order of elements matters.

You can also try
var $contents = $('.content');
var $imgs = $('.circle_hiw_cont img').click(function() {
var $target = $('#content_' + this.id.replace('content_img_', '')).show();
$contents.not($target).hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="circle_hiw_cont">
<img id="content_img_1" src="//placehold.it/64/ff0000" />
<img id="content_img_2" src="//placehold.it/64/00ff00" />
<img id="content_img_3" src="//placehold.it/64/0000ff" />
<div id="content_1" class="content">This is div 1</div>
<div id="content_2" class="content">This is div 2</div>
<div id="content_3" class="content">This is div 3</div>
</div>

if which div is shown is predefined, that should work:
$('.circle_hiw_cont img').click(
function() {
if( $(this).attr('src') === "content_img_1.jpg") {
$("#content_1, #content_2, #content_3").toggle();
} else {
}
}
);

You actually weren't too far off, this is going to refer to the current DOM node though, not the src of the image as your code assumes:
$('.circle_hiw_cont img').click(
function() {
if(this.src == "content_img_1.jpg") {
$("#content_1").css("display", "block");
$("#content_2").css("display", "none");
$("#content_3").css("display", "none");
} else {
}
}
);

The context this in the function call refers to the DOM element that was clicked. You will need to compare the appropriate attribute, instead.
$('.circle_hiw_cont img').click(
function() {
var $this = $(this);
if($this.attr('href') == 'content_img_1.jpg') {
...
} else {
}
}
);

Provide some class name to all the images say "imgClass" and
$('.imgClass').click(
function() {
$("#content_1").css("display", "block");
$("#content_2").css("display", "none");
$("#content_3").css("display", "none");
}
);

Related

JS function won't hide element

I'm trying to hide or show a div when clicking on a link.
This is the HTML part that I want to show or hide:
<div id="product">
<div ng-repeat="producto in productos" >
<figure class="floating">
<img ng-src="{{ producto.image }}" alt="image" class="rcorners3" style='width:100%;' border="0" alt="Null">
<figcaption> {{ producto.name }}</figcaption>
</figure>
</div>
</div>
When clicking this:
<li onclick="isitvisible()" class="guides">
And this is the script I run when clicking:
<script type="text/javascript">
function isitvisible() {
var vale = document.getElementById('product').offsetLeft;
if (vale <= 0) {
document.getElementById('product').style.visibility='hidden';
} else {
document.getElementById('product').style.visibility='visible';
}
}
</script>
The div would hide but not show at all after clicking. I think I'm failing with the offsetLeft but not sure.
offsetLeft doesn't change when you toggle a element's visibility.
Try this isitvisible function instead:
function isitvisible() {
// Get a reference to the element's style.
var style = document.getElementById('product').style;
if (style.visibility === 'hidden') {
style.visibility = 'visible';
} else {
style.visibility = 'hidden';
}
}
Or a little shorter:
function isitvisible() {
var style = document.getElementById('product').style;
style.visibility = (style.visibility === 'hidden') ? 'visible' : 'hidden';
}
Change it to this:
<script type="text/javascript">
var style = document.getElementById('product').style;
function isitvisible() {
if (style.display=='none') {
style.display='block';
} else {
style.display='none';
}
}
</script>

For each div with same class do something

I have some divs with same class. Inside this divs i added another div to put an ad.
Now i am trying to hide the ad div if the width of the div that holds my ad div is equal to 366px;
I tried the code bellow but it hides only my first ad div..
Example:
<div class="masterdiv">
<div id="myaddiv"></div>
</div>
<div class="masterdiv">
<div id="myaddiv"></div>
</div>
<div class="masterdiv">
<div id="myaddiv"></div>
</div>
and my jquery code is:
var adwidth = $(".masterdiv").width();
if (adwidth == 366){
$('#myaddiv').hide();
}
Thank you!
Because var adwidth = $(".masterdiv").width(); only returns the first value. The answer is in your title, you need to use each. Another issue is ids are SINGULAR, so you need to use a class
Using each:
$(".masterdiv").each( function() {
var elem = $(this);
var width = elem.width();
if (width == 366){
elem.find('.myaddiv').hide(); //use a class since only one element can have an id
}
});
Using filter:
$(".masterdiv").filter( function() {
return ($(this).width() == 366);
}).find('.myaddiv').hide();
The updated HTML:
<div class="masterdiv">
<div class="myaddiv"></div>
</div>
you should not use duplicate ids.use:
$('div .masterdiv').each(function(){
if($(this).width()==366){
$(this).find('div').hide();
}});
Try:
$('.masterdiv').each(function(){
if($(this).width()==386){
$(this).hide();
}
});
This is only doing the first div because you are using id's instead of classes. Since there can only be one id per page javascript stops after matching the first one. change to classes and you should be fine.
you are using same id's for different divs
Instead of id, give class name
<div class="masterdiv">
<div class="myaddiv">
</div>
</div>
<div class="masterdiv">
<div class="myaddiv">
</div>
</div>
<div class="masterdiv">
<div class="myaddiv">
</div>
</div>
$(document).ready(function () {
var adwidth = $(".masterdiv");
for (i = 0; i < adwidth.length; i++) {
if ($(adwidth[0]).attr("width") == 366) {
$(this).find('.myaddiv').hide()
}
}
});
$(".masterdiv").each(function(){
var current = $(this);
if(current.width() == 366) {
current.hide();
}
});
You have to change in this way:
$('#myaddiv', '.masterdiv').each(function() {
var width = $(this).width();
(width > 366) ? $(this).hide() : 0;
});
You can try on this live DEMO

Add Class to Following Element

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>

How can I shorten this javascript code? show hide multiple divs

How can I shorten this code? Each css selector increases +1. All Bio's divs are hidden unless the .mug(x) is selected.
Thanks
<script type='text/javascript'>
$(document).ready(function () {
$(".mug1").click(function() {
$("#bios div").hide();
$(".bio1").show();
});
$(".mug2").click(function() {
$("#bios div").hide();
$(".bio2").show();
});
$(".mug3").click(function() {
$("#bios div").hide();
$(".bio3").show();
});
});
</script>
<h2>Meet the team</h2>
<div id="mugshots">
<img src="images/img-mugshot.jpg" alt="mug" class="mug1"/>
<img src="images/img-mugshot.jpg" alt="mug" class="mug2"/>
<img src="images/img-mugshot.jpg" alt="mug" class="mug3"/>
</div>
<div id="bios">
<div class="bio1"></div>
<div class="bio2"></div>
<div class="bio3"></div>
</div>
Something along these lines?
Change the html to this:
<div id="bios">
<div class="bio" data-id="1"></div>
<div class="bio" data-id="2"></div>
<div class="bio" data-id="3"></div>
</div>
Then your js to this:
$(".mug").click(function() {
$("#bios div").hide();
$(".bio[data-id='" + $(this).data("id") + "'", $("#bios")).show();
});
This way you could add as many mugs and bios as you like without having to add any more js.
Simplest way is a for loop
$(document).ready(function () {
for (var i = 1; i <= 3; i++) {
$(".mug" + i).click(function() {
$("#bios div").hide();
$(".bio" + i).show();
});
}
});
There may be a better way still that I'm not thinking of.
just use index and add as many as you want:
$('#mugshots>img').on('click', function() {
$("#bios div").hide();
var myIndex = $(this).index("#mugshots> img");
$("#bios> div").eq(myIndex).show();
});
a shorter version of this is:
$('#mugshots>img').on('click', function() {
$("#bios div").hide().eq($(this).index("#mugshots> img")).show();;
});
Use the .eq() and the index of your mugshots, assuming the first mugshot goes with the first bio, second mugshot with second bio, and so on.
http://api.jquery.com/eq/
Also, use a class to keep track of your active bio rather than calling hide on all bios for each update.
JS:
$(document).ready(function() {
$('#mugshots img').click(function() {
$('#bios .active').hide().removeClass('active');
$('#bios div').eq($(this).index()).show().addClass('active');
});
});
HTML:
<h2>Meet the team</h2>
<div id="mugshots">
<img src="images/img-mugshot.jpg" alt="mug"/>
<img src="images/img-mugshot.jpg" alt="mug"/>
<img src="images/img-mugshot.jpg" alt="mug"/>
</div>
<div id="bios">
<div></div>
<div></div>
<div></div>
</div>
try this:
$(document).ready(function () {
$("img[alt=mug]").each(function() {
$(this).click(function(){
var id = $(this).attr("class").substr(3, 1);
$("#bios div").hide();
$(".bio" + id).show();
});
});
});

jQuery code refactoring help needed

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>

Categories

Resources