JQuery change image in div - javascript

I don't think I am doing this the best way possible. Is a better way to do it?
Example: http://www.mudquarters.com (click "in stores")
I want to default to the blue shirt and when you click the swatches they swap the image in the div to the appropriate color. They are somewhat working now, however it defaults to yellow instead of blue and this method requires my css to include position: "absolute" which ruins my background tiling for that section in my responsive layout as it is breaking outside the container.
Is there a way to do this better?
CSS:
#shirt img {
position:absolute;
}
HTML:
<ul id="swatches">
<li><img src="img/BTN_Blue.gif"></li>
<li><img src="img/BTN_Green.gif"></li>
<li><img src="img/BTN_Red.gif"></li>
<li><img src="img/BTN_Grey.gif"></li>
<li><img src="img/BTN_Yellow.gif"></li>
</ul>
<div id="shirt" class="large-6 columns">
<img src="img/T_Blue.png">
<img src="img/T_Green.png">
<img src="img/T_Red.png">
<img src="img/T_Grey.png">
<img src="img/T_Yellow.png">
</div>
JS:
<script>
$('#swatches li').on('mousedown',function(e){
$('#shirt img').stop().fadeTo(300,0);
if (e.type=='mousedown') {
$('#shirt img').eq( $(this).index() ).stop().fadeTo(300,1);
}
});
</script>

Fixes
Issue 1: In order to default to the blue shirt, you can just hide all other images on page load:
$('#shirt img').not(':first').fadeOut(0);
Issue 2: The issue with absolute positioned elements is that they are outside the flow, so parents can't adjust their height. The only fix for this would be to set the height explicitly, taking a note from James Daly's answer you would need something like this (inside the resize event to accommodate for your fluid layout):
$(window).resize(function() {
$('#shirt').height($('$shirt img:first').height());
});
$(window).trigger('resize');
New approach
Now if you don't feel like implementing this fixes, you can change your logic to use only one image and update its src with the click on the swatches, effectively eliminating both issues since there won't be a need to use absolute position anymore and you could easily set the default image to blue. This new implementation would look something like this:
HTML
<ul id="swatches">
<!--Add the reference to the main img src of each link as a data-attribute-->
<li><img src="img/BTN_Blue.gif"></li>
<li><img src="img/BTN_Green.gif"></li>
<li><img src="img/BTN_Red.gif"></li>
<li><img src="img/BTN_Grey.gif"></li>
<li><img src="img/BTN_Yellow.gif"></li>
</ul>
<div id="shirt" class="large-6 columns">
<img src="img/T_Blue.png"> <!--Set blue as default-->
</div>
jQuery
var $shirtImg = $('#shirt img');
$('#swatches li a').on('mousedown',function(e){
var src = $(this).data('img-src');
if(src != $shirtImg.attr('src')){ //Check if it's not the image we have now
$shirtImg.stop().fadeTo(150,0.8,function(){
$(this).attr('src',src).fadeTo(150,1);
});
}
});

A couple of things you could try ... I can't tell for sure though.
To get the blue shirt to display by default, could you not change the order of the images and place the blue shirt last?
<div id="shirt" class="large-6 columns">
<img src="img/T_Green.png">
<img src="img/T_Red.png">
<img src="img/T_Grey.png">
<img src="img/T_Yellow.png">
<img src="img/T_Blue.png">
</div>
For the background tiling, try adding overflow:auto; to the style for #stores
Good luck!

css
.zindex { z-index: 10}
edit
try making the parent div as tall as the image
javascript
var $firstImage = $('#shirt img:first-child'); // cache
var imageHeight = $firstImage.height();
$firstImage.addClass('zindex');
var $shirtImage = $('#shirt img')
$('#shirt').height(imageHeight);
$('#swatches li').on('mousedown',function(e){
$shirtImage.removeClass('zindex').stop().fadeTo(300,0);
if (e.type=='mousedown') {
$shirtImage.eq( $(this).index() ).stop().fadeTo(300,1);
}
});
it doesn't look like you are changing the image size at all when screen is small if so you could always wrap that in a function and call it on
$(window).resize(function() {
// your code here
})

Related

How to change image when I hover then return to original image only when I hover again

I have two images, what I want to happen is that when I hover on the image, the image will change to the second image, and then when I hover on the image again, the image will change to the first image.
How do I do that using JavaScript?
This is a Javascript solution. I highly suggest you look into Jquery once you understand the below. In your case you don't seems to need the onmouseout.
HTML
<img src="urImg.png" onmouseover="chgImg(this)" onmouseout="normalImg(this)">
Javascript
function chgImg(x) {
x.src = "newImg.png";
}
function normalImg(x) {
x.src = "urImg.png";
}
HTML
<div class="image_container">
<img src="foo.png" class="first"/>
<img src="bar.png" class="last"/>
</div>
jQuery
$(".image_container").hover(function(){
$(this).toggleClass("switch");
});
CSS
.image_container .last{display:none;}
.image_container.switch .last{display:block;}
.image_container.switch .first{display:none;}
You can do this!
<a href="#" id="name">
<img title="Hello" src="images/view2.jpg>
</a>
$('#name img').hover(function() {
$(this).attr('src', 'images/view1.jpg');
}, function() {
$(this).attr('src', 'images/view2.jpg');
});
For anyone who do not want to use Javascript, just HTML, CSS.
You just need create second image with position: absolute; and put it with original image into a div (with position: relative;)
After that, you can use CSS to control opacity of second image when you hover it.
Below is my sample code using TailwindCSS
<div className="relative">
<img
src="/image1.png"
className="w-[100px] h-[100px]"/>
<img
src="/image1.png"
className="w-[100px] h-[100px] absolute opacity-[0] hover:opacity-[1]"/>
</div>

Javascript: Show one element, hide another

Taking a web design course, and need to use strictly Javascript on this project.
Basically I want to have a series of thumbnails on the left of the screen, and when one is hovered over it brings up information about the image on the right side of the screen. It remains that way until another thumbnail is hovered over, then the information is replaced.
I thought of having a series of divs on-top of eachother containing the information, and onhover the targeted div appears and the last div disappears.
Any suggestions?
Give the images a mouseover attribute and run a function on hover.
<img onmouseover="changeInfo(0)">
<img onmouseover="changeInfo(1)">
<img onmouseover="changeInfo(2)">
<div id="showInfo"></div>
Then place the info for every image in an array and change the inner html in the div depending on which image is being hovered.
function changeInfo(index){
var texts = ['Info on img0','Info on img1','Info on img2'];
var info = document.getElementById('showInfo');
info.innerHTML = texts[index];
}
I don't know if this is the result you want to get. First, I declare all the images using divs. The information is hidden at the beginning.
<div id="posts">
<div id="post1">
<img src="[Insert an image]" width="100" height="100"/>
<p class="hide"> information about picture one </p>
</div>
<div id="post2">
<img src="[Insert an image]" width="100" height="100"/>
<p class="hide"> information about picture one </p>
</div>
<div id="post3">
<img src="[Insert an image]" width="100" height="100"/>
<p class="hide"> information about picture one </p>
</div>
</div>
these are the css classes
.nolabel p {display: none;}
.label p { display: block; }
.hide { display: none; }
and javascript:
var posts = document.getElementById("posts").children;
function forEach(el, callback) {
for(var i = 0; i <= el.length; i++) {
callback(posts[i]);
}
}
forEach(posts, function(child) {
child.addEventListener("mouseover", function(){
forEach(posts, function(el) {
if(child.id === el.id)
el.className = "label";
else
el.className = "nolabel";
});
});
});
the forEach helps us to simplify a this code a little.
Since we could have any number of images I thought it was not a good
idea to reference each of them by its id.
When the cursor hovers over one of the images we trigger a mouseover event which will compare the ids. The if statement makes sure we only modify the element we clicked and the others remain with the nolabel class (or replace it if they had label).
I hope that helps.
jQuery would be best for this, or you can use an onMouseOver function and your information styled with visibility: hidden. Maybe post some code so more help can be provided.
Check this out too Display text on MouseOver for image in html

Execute jquery function after image has loaded on window resize

I have the following javascript function:
function reglare(){
alert("Inaltime imagine= "+$(".slider img").height());
}
I call the function on window resize, like this:
$(window).resize(function(){
reglare();
});
Most of the times the output is the image height, but sometimes the output is 0.
How can I fix this in order to get the actual image size on window resize ALL the times?
LATER EDIT: why do I need this?
The code is like this:
<div id="slideshow" class="latime_100">
<img src="poze/sageata_st.png" class="navigare" id="navigare_st" onclick="go_prev();"></img>
<div id="slider_1" class="slider" >
<img src="../poze/imagine_slide1_iul_fade.png"></img>
</div>
<div id="slider_2" class="slider">
<img src="../poze/imagine_slide2_iul_fade.png"></img>
</div>
<div id="slider_3" class="slider">
<img src="../poze/imagine_slide3_iul_fade.png"></img>
</div>
<img src="poze/sageata_dr.png" class="navigare" id="navigare_dr" onclick="go_next();"></img>
</div>
I have a container div slideshow which is position relative containing more absolute positioned divs. Because they are position absolute, the container does not extend with content so what is below gets overlapped.
Here's a fiddle: https://jsfiddle.net/g6ppqxLf/5/
TO DISPLAY THE ERROR I HAVE IN THE FIDDLE: just resize the browser a few times and follow the alert message: it will sometimes output 0.
the jquery class selector returns an array.
https://api.jquery.com/class-selector/
function reglare(){
for (var i = 0; i < $("img.slider").length; i++){
alert($("img.slider")[i].attr("height");
}
}
this alerts the attribute height of each image with class .slider
hope this is what you searched for

JQUERY 1.7.1 toggle li id not working

I'm using the code presented here: http://trevordavis.net/blog/simple-jquery-text-resizer so that my visitors can re-size the page texts. I like this method except for the fact that it uses 3 buttons to change text size. I've got the re-size buttonS working but what I'm trying to accomplish now is to get it looping my buttons (display:block - display:none). ei: if text size small, show medium button, if text size medium show large button, if text large, show small button, as opposed to having the 3 buttons show all the time.
I'm using jquery-1.7.1.min.js (toggle was not yet retired).
My text resize part of the code works, but not the toggling buttons. There could be hope in doing the toggling on an ID instead of class but, not being fluent in js, I have not figured out how to do target the id instead of the class, and I don't know that that is what is wrong with code in the first place.
Here is my code:
<script type="text/javascript" src="../js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="../js/jquery.cookie.js"></script>
<script type="text/javascript">
/*set resizer cookie*/
$(document).ready(function() {
if($.cookie('TEXT_SIZE')) {
$('body').addClass($.cookie('TEXT_SIZE'));
} else {
$('body').addClass("small");
}
/*set resizer class to body*/
$('.resizer a').click(function() {
var textSize = $(this).parent().attr('class');
$('body').removeClass('small medium large').addClass(textSize);
$.cookie('TEXT_SIZE',textSize, { path: '/', expires: 10000 });
return false;
/*show the proper button (for looping sizes, from small to large, back to small ---NOT WORKING*/
$('.toggle').hide();
if (textSize = 'small') {elem = "medium" };
if (textSize = 'medium') {elem = "large" } ;
if (textSize = 'large') {elem = "small" };
$('.toggle').not(elem).hide();
elem.toggle();
});
});
</script>
<ul class="resizer" id="link">
<li class="small" id="small" style="display: block;"> <img alt="larger" width="22" height="16" src="../Images/BaseFiles/glyphicons_115_text_smaller.png"/></li>
<li class="medium" id="medium" style="display: none;"><img alt="larger" width="22" height="16" src="../Images/BaseFiles/glyphicons_116_text_bigger.png"/></li>
<li class="large" id="large" style="display: none;"> <img alt="smaller" width="22" height="16" src="../Images/BaseFiles/glyphicons_116_text_bigger.png"/></li>
</ul>
Thank you for any help!
working example
in your code looping sizes block goes after the "return false" expression, which ends any futher execution of the script in the "click" function.
there are also some mistakes with manipulating classes in jquery
like this:
if (textSize == 'small') {elem = ".medium" };

How to change style of HTML element depending on another elements style?

In my Web application i am changing style of HTML Element using javascript.
See be below code,
function layout() {
if(document.getElementById('sh1').getAttribute('src') == "abc.png") {
document.getElementById("sh1").style.display="none";
} else {
document.getElementById("sh1").style.display="block";
}
}
and HTML is :
<img id="sh1" src="abc.png" />
Now i want that if img elements style is display:none; then below Elements
<p id="Text1">Name<br />description</p>
style should also get changed to display:none; and if img elements style is display:block; then above Elements style should also get changed to display:block; automatically.
how this can get achieved?
Add the other element in your function too. Something like this:
function layout(){
if(document.getElementById('sh1').getAttribute('src') == "abc.png"){
document.getElementById("sh1").style.display="none";
document.getElementById("Text1").style.display="none";
} else {
document.getElementById("sh1").style.display="block";
document.getElementById("Text1").style.display="Block";
}
}
or if you put both in a container you can do one operation on the whole container =)
If i've understood you correctly then your after this
function layout(){
if(document.getElementById('sh1').getAttribute('src') == "abc.png"){
document.getElementById("sh1").style.display="none";
document.getElementById("Text1").style.display = "none"; //Hide the description
} else {
document.getElementById("sh1").style.display="block";
document.getElementById("Text1").style.display="block"; //Show the description
}
}
If this function is unique to this image and desciption then this should work nicely, obviously if there are a whole bunch of images that you are applying this logic to then there is a much more efficient way of achieving this with a generic function.
I would recommend just using jQuery and changing the markup to wrap your image and text together. Check out the link to a working example too.
<figure id="sh1" class="picture active">
<img src="http://placehold.it/100x100&text=abc.png" />
<figcaption><span class="name">ABC</span><span class="desc">This is a description</span>
</figcaption>
</figure>
<figure id="sh2" class="picture">
<img src="http://placehold.it/100x100&text=xyz.png" />
<figcaption><span class="name">XYZ</span><span class="desc">This is a description</span>
</figcaption>
</figure>
http://jsfiddle.net/Qvb4U/1/

Categories

Resources