Change Another Image On Link Hover - javascript

The output in HTML is something like this:
ProductImage1 ProductImage2 ProductImage3 ProductImage4
Color1 Color2 Color3 Color2 Color4 Color5 Color6
What I want to do is when I hover my mouse over any color above, an original (current) image of ProductImage will change to another one (to match the hovered color). And that original image will be back when mouse leaves.
Here is the javascript I've done for hovering over each ProductImage.
var sourceSwap = function () {
var $this = $(this);
var newSource = $this.data('alt-src');
$this.data('alt-src', $this.attr('src'));
$this.attr('src', newSource);
}
$(function () {
$('img.main').hover(sourceSwap, sourceSwap);
});
UPDATE
I excluded unnecessary parts from my question. The answer from #hunter worked very well when I tested it here jsfiddle.net/4dK2x/27. However it didn't work when I combined it with my php parts to create dynamic lists. I'm still looking around and trying to find out the problems. I will come back and update my answer if I find a solution for it.

Here's updated code which should work with as many sets of products as you need if you mimic a similar html structure
$('.image .toggles img').hover(function () {
var src = $(this).attr("src");
var $main = $(this).closest(".image").find(".main");
$main.attr("toggle", $main.attr("src")).attr("src", src);
},
function () {
var $main = $(this).closest(".image").find(".main");
$main.attr("src", $main.attr("toggle"));
});
Example: http://jsfiddle.net/4dK2x/1/

You could do this two ways, you can try it by using CSS:
#tagName{
background: url("yourImage.jpg");
}
#tagName:hover{
background: url("anotherImage.jpg");
}
this assumes you have a div tag around the image, you can also reference class id's etc. (read into CSS for more details).
or you could do it through JavaScript
lets say you are not using JQuery (i need to familiarize myself more with JQuery)
var image1 = document.getElementById("nameofDivTag");
//on hovering kinda forgotten the JS version of hovering, JQuery has probably easier way
image1.style.background("url:("aDifferentImage.jpg"));
if i am wrong yay! if not yay!
hope it helps

Related

jQuery show() doesn't work after hide()

I'm trying to display div with content after click on image, but when my page is loaded and I try to click then nothing happens. Interesting that if my page is loading with not hidden content and then I'll do hide() and after that show() id console then it works perfectly. What am I doing wrong?
$(document).ready(function() {
$('.content-flowers').hide()
var first = $(".content-flowers").children()[0];
var second = $(".content-flowers").children()[1];
var third = $(".content-flowers").children()[2];
var firstImg = $(".flower-image")[0];
var secondImg = $(".flower-image")[1];
var thirdImg = $(".flower-image")[2];
$(firstImg).click(function(){
$(first).toggle(1000);
})
/*$(".flower-image").click(function () {
$('.content-flowers').show(1000);
});*/
});
Last commented function works also good, but that function loads all three divs with content, I want in order to after click on 1 image the first div with content will display
You've said the commented-out version works other than that it does all three at the same time, but the earlier version does not work.
They do very different things. Your un-commented-out code looks at the children of the .content-flowers elements:
var first = $(".content-flowers").children()[0];
But your commented-out version works on the .content-flowers elements themselves:
$('.content-flowers').show(1000);
I suspect it's the .children() part that's making it fail. I think you want:
var first = $(".content-flowers")[0];
// No .children() here ----------^
...as the minimal change.
That said, though, the whole thing can be dramatically simpler:
$(document).ready(function() {
$('.content-flowers').hide()
// Get the flower images
var images = $(".flower-image");
// When a flower image is clicked...
images.on("click", function() {
// Determine its index relative to the others...
var index = images.index(this);
// And show that content
$(".content-flowers").eq(index).toggle(1000);
});
});
You already applied the jquery function on the variable first. So try first.toggle(1000) instead. Remove the $ sign.

How to make a grid of interactive elements?

I'm trying to create a portfolio website that resembles this, a full-page grid of images that change when you hover over them... (another example, the third screen!)
And currently I have a crude solution that looks like:
<img src="1.png" id="img" swap="2.png"/>
// then in JS...
$("#img").hover(function(){
var _this = $(this);
var current = _this.attr("src");
var swap = _this.attr("swap");
_this.attr('src',swap).attr('swap',current);
}); //
code credit
But this isn't a very scaleable solution and other than having 1000 images, each with their own unique ID which is identified so the src can be toggled, I'm not sure what to do -- plus I don't know how this would react to different display sizes/screen cut-offs. And while background-image in CSS tiles nicely, it doesn't allow interactivity... unless maybe you had a JS script track cursor position(?)
!! This is my very first project, any help would be appreciated :) (Codecademy is a very sheltered learning environment........)
you don't have to use ids and create a handler for every image.
this will apply to every image CURRENTLY on the page:
$("img").hover(function(){
var _this = $(this);
var current = _this.attr("src");
var swap = _this.attr("swap");
_this.attr('src',swap).attr('swap',current);
});
and this will react to every image, even images added after the page is loaded:
$(document).on('hover', 'img', function () {
var _this = $(this);
var current = _this.attr("src");
var swap = _this.attr("swap");
_this.attr('src',swap).attr('swap',current);
});
To account for screen sizes and your other concerns, you'd need to either set a fixed width and height on your images, or make sure all your images are of similar resolution.
You could do this with backgrounds as well by creating a grid of divs then change the background of the div on hover, similar to the above handlers.

Replace ending on multiple img src

I have 10 buttons each with a different image and text. I have each button to click on/off and if another button is clicked I want the active button to turn off. I am struggling with the latter.
var x = 300;
//port1
$('#port1').click(
function(){
var src = $('.image', this).attr('src');
//var srcs = $(this).attr('src');
if($(this).hasClass("highlight")) {
$('.butt').removeClass('highlight');
$('.image', this).attr('src', src.replace(/_dark(\.[^.]+)?$/, '_light$1'));
$('.p1').fadeOut(x);
}
else{
$('.butt').removeClass('highlight');
// $('.butt').attr('src').replace('_dark.png', '_light.png');
$('.butt img').each(function() {
var src2 = $('.image').attr('src').replace(/_dark(\.[^.]+)?$/, '_light$1');
$('.image').attr('src', src2);
});
$('.talk').fadeOut(x);
$(this).addClass('highlight');
$('.image', this).attr('src', src.replace(/_light(\.[^.]+)?$/, '_dark$1'));
$('.p0').fadeOut(x);
$('.p1').fadeIn(x);
}
});
The problem I am running into is that when I click the button, it changes the src on all the other buttons to be exactly the same as this one and does not just change the ending on the other sources to '_dark'. I thought adding this 'each' function would help and it did not.
Edit: I am new to coding but i attempted a jsfiddle: http://jsfiddle.net/messedUP90/yxjoxe41/
The random computers that appear was the effect I am going for and the code I wrote to do it before I remembered that each icon was going to be different. Look at the first button titled "un" for where the error I am talking about happens.
http://jsfiddle.net/gtf1dk0m/1/
You need to re-set the variable src.
This code does it:
$('.butt').each( function( index ) {
if ( $(this).attr('src') ) {
$(this).attr('src', $(this).attr('src').replace(/_dark(\.[^.]+)?$/, '_light$1'));
}
});
ignore the fact that the image does not change color in the jsfiddle. it works in dreamweaver. :)
There is some strange code and naming conventions in this function... such as var src = $('.image', this).attr('src');... theres a lot unexplained by the question asked here and with no jsfiddle it's hard to imagine what you mean or see what HTML elements you're using...
so I will try to answer based on purely your description and not your code.
If you want to remove all instances of a class such as an active class you could simply do an each function however your later comments about it changing all other image sources once clicked is in this line $('.image').attr('src', src2);. You have effectively targeted all images under the class .butt which seems to be all of your images. Perhaps what you want is actually to iterate over all elements and remove the active state such as...
$(".butt img").each(function() {
//Remove Active Classes
if($(this).hasClass("activeImage")) {
$(this).removeClass("activeImage");
}
});
Then you are now free to take the clicked button and add its active state in...
$(".buttons").each(function() {
$(this).click(function() {
//Old Code
$(".butt img").each(function() {
//Remove Active Classes
if($(this).hasClass("activeImage")) {
$(this).removeClass("activeImage");
}
});
//New Code
$(this).addClass("activeImage");
});
});
Then in your CSS you could make sure that you have a rule like
.activeImage {
background-image: url("blah.png") !important;
/* You Get The Idea */
}

Multiple, unique, popup windows with JPopUp script?

I know this has probably been answered multiple times before, but this is the second time I've worked with JQuery, and I'm not entirely sure what I need to do, since I'm not familiar with this format of coding. I've looked at other, similar, questions, but none of the answers are making sense to me, and I really need this to click in my head so I can keep working.
I'm using Jpopup for this, so the script info is all there, but my question is this:
I have two areas in an image that I need to be clickable, both showing different content, but I can only call one page at a time to pop up, and multiple anchor tags just give me the same content twice. What do I need to add to that script to allow the page to show two different popups?
This is the script in my HTML page
<script language="javascript">
$(document).ready(function() {
//Change these values to style your modal popup
var source = "demo.html";
var width = 920;
var align = "center";
var top = 100;
var padding = 10;
var backgroundColor = "#FFFFFF";
var source = 'popups/demo.html';
var borderColor = "#000000";
var borderWeight = 4;
var borderRadius = 5;
var fadeOutTime = 300;
var disableColor = "#666666";
var disableOpacity = 40;
var loadingImage = "popups/loading.gif";
//This method initialises the modal popup
$(".modal").click(function() {
modalPopup( align,
top,
width,
padding,
disableColor,
disableOpacity,
backgroundColor,
borderColor,
borderWeight,
borderRadius,
fadeOutTime,
source,
loadingImage );
});
//This method hides the popup when the escape key is pressed
$(document).keyup(function(e) {
if (e.keyCode == 27) {
closePopup(fadeOutTime);
}
});
});
</script>
The HTML
<div style="margin-top:200px;margin-left:395px;">
<a class="modal" href="javascript:void(0);"><img src="images/clickmelarge.png" border="0">
</a></div>
I studied the source code of the "plugin" and studied also the invoked source code of the HTML page at runtime. In my eyes this popup plugin doesn't support multiple popups at same time. Why?
Well, I used Firebug to exermine the source code at runtime and I saw only the same divs, added to the DOM tree by this. As far as I did understand when the DOM was complete loaded the author added the main divs to the DOM tree and set they all to 'hide'. If you call your function these divs will set to 'visible'.
Another reason is -in my eyes a very tricky way- the div with the Id 'blockModalPopupDiv' covers the full browser window. If you click on this element, the function of hiding all divs will be executed. You won't be have chance to click outside the div element.
So what can you do?
I think you have only three options :
Ask the author for an opportuniti to add your requirement.
Download the source code and modifiy it your self. Its created in standard Javascript.
Try to use another plugin or change your concept.

Regular Expression to replace src attribute of img tag

I need a regular expression that will properly work, the current one I have is breaking.
The goal is
Normal src for an image is:
Image.png
Using jQuery on hover I dynamically find the src of an image and replace it with ImageName-Dn.png
On hover off it sets it back to ImageName.png
My current solution:
$(document).ready(function(){
$(".myButton").hover(
function () {
var s = $(this).attr('src');
s = s.substring( 0, s.search(/(\.[a-z]+)$/) ) + '-Dn' + s.match(/(\.[a-z]+)$/)[0];
$(this).attr('src', s);
},
function () {
var o = $(this).attr('src');
o = o.replace(/-Dn\./, '.');
$(this).attr('src', o);
}
);
});
However for some reason the image at some point gets set to ImageName-Dn.png and then screws up and gets set to ImageName-Dn-Dn.png and so on and so forth. Any Help?
A quick fix is to test if the string doesn't already have -Dn in it:
if (!string.match(/-Dn\./))
Also, with the regexes, you don't need to manually split the string and do multiple searches. You can use grouping to receive what you need in a single replace instruction such as:
string.replace(/(.*)\.(.*)/, "$1-Dn.$2")
If you want to read up on regular expressions for Javascript: http://en.wikibooks.org/wiki/JavaScript/Regular_Expressions
are you doing this for a mouseover effect? Why not use image sprites? Effectively, you just need to create 1 image that contains both version of the image side by side and set it to the background of an element which will display it.
for example, a 10x10 image and it's mouseover version will become a 10x20 image with the original on top of the mouseover version.
you can then create a 10x10 div with the background-image set to the 10x20 image. Since only the top 10x10 will be displayed, you only see the original version.
Then in javascript you can simply attach to an event a call to
$(el).style.backgroundPosition = '0px -10px';
on the hover event and
$(el).style.backgroundPosition = '0px 0px';
to reset it
This will shift the background up on the mouse over. Not only is this cleaner than having to deal with regex for a simple image swap, it also reduces the number of files the page has to load.
Hope this helps!
function () {
var s = $(this).attr('src');
if( !s.match(/-Dn\.[a-z]+$/) ) {
s = s.substring( 0, s.search(/(\.[a-z]+)$/) ) + '-Dn' + s.match(/(\.[a-z]+)$/)[0];
$(this).attr('src', s);
}
},
function () {
var o = $(this).attr('src');
o = o.replace(/-Dn\./, '.');
$(this).attr('src', o);
}
(added conditional)

Categories