Couldn't find a punctual answer for this simple task and your help is highly appreciated
We have an image we want to switch based on user's color selection.
Tried several methods, none worked.
This is the idea:
$('#YourButton').click(function() {
var oldSrc = 'images/Image1.png';
var newSrc = 'images/Image2.png';
$('img[src="' + oldSrc + '"]').attr('src', newSrc);
});
Just change the image source with javascript by clicking your button with another color
Note: it´s jquery so you have to include the js file..
Just bind a click listener to your button and change the src attribute of your image.
$('#colorButton').click( function() { //choose a new color
$('#imageIcon').attr('src', 'path/to/new/image.png'); //change the img's source
});
EDIT (response to questions):
If you want this code to apply to all of your buttons, give each of your buttons a similar class instead of an ID:
<div class="colorButton"></div>
Then you can use the following selector to apply the above click listener to all of these divs:
$('.colorButton')
Naturally, you want to change your image as simply as possible. You could map all of your colors to their corresponding image file, but as far as design goes this might get messy and unwieldy. I would create a directory that stores all of your image files (for example, /your/color/swatches) and give each of them a name consistent with their color, like 'ff0000.png' for red, '0000ff.png' for blue, etc.
Why would we do this? So that we can switch your image based on the background-color attribute of your buttons. Let's say that you have the following buttons:
<div class="colorButton" style="background-color: '#ff0000'"></div>
<div class="colorButton" style="background-color: '#0000ff'"></div>
You can use the same click listener, but it will have to be modified a bit since we are mapping the background color to an image:
$('.colorButton').click( function() {
var color = $(this).css('backgroundColor');
//(You'll need to modify your color string here)
$('#imageIcon').attr('src', 'your/color/swatches/' + color + '.png');
});
BUT this won't work yet. Since most browsers return "rgb(xx, yy, zz)" from .css('backgroundColor'), you need to convert that string into hex. This post on SO gives a more or less effective way to do so, but you'll need to modify it to fit your model where I have indicated.
Related
I'm testing out some jQuery and want to update a image when hovering over a specific div or link block.
So what i was trying to do is when hovering over .test-block get the hidden text with the url and update it on .large-image-2. It can't seem to get the specific text on hover.
This is the code i have come up with:
$('.test-block').on('onmouseenter', function() {
let myUrl = $(this).find('.display-hidden').text();
$('.url').text(myUrl);
});
Im testing on this page: https://jquery-testing.webflow.io/update-image the three bottom div's and bottom picture on right is what i want to use.
Thanks in advance!
There are a few issues with your example. Mainly the way you register the event handler.
For jQuery the correct way would be $(target).on('mouseenter') - Ommit the on... part for the event you want to register when doing it through jQuery.
I would probably implement the functionality you're looking for in a less specific way and with simpler handles like the following:
$(function () {
let divs = $('[data-image-target][data-image-url]');
divs.on('mouseenter', function () {
let that = $(this)
const target = that.data('image-target')
const url = that.data('image-url')
$(target).attr('src', url);
})
divs.first().trigger('mouseenter')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div
data-image-target="#my-target-image"
data-image-url="https://dummyimage.com/600x400/000/fff&text=one">
Hover One
</div>
<div
data-image-target="#my-target-image"
data-image-url="https://dummyimage.com/600x400/000/fff&text=two">
Hover Two
</div>
<div
data-image-target="#my-target-image"
data-image-url="https://dummyimage.com/600x400/000/fff&text=three">
Hover Three
</div>
<img id="my-target-image">
Explanation:
Data attributes:
Two data attributes are getting used in my example: data-image-target and data-image-url.
Using data attributes on the elements you want the event to be fired on will make your script a bit more robust and less prone to errors, since the event registration is bound to the two attributes being present using attribute selectors for the jQuery selector $([data-image-target][data-image-url]) instead of arbitrary classnames and/or ids.
The data-image-target should have a CSS selector that points to the <img> element(s) you wish to switch the src url on, while the data-image-url should hold the url of the image you want to switch to.
The code above could even replace your existing functionality for the top 3 images on your page.
This code worked
$(function () {
let divs = $('[data-image-target][data-image-url]');
divs.on('mouseenter', function () {
let that = $(this);
const target = that.data('image-target');
const url = that.data('image-url');
$(target).attr('src', url);
});
});
Thanks to Morten for providing. With Webflow i also had to do Command + Shift + O to turn off responsiveness to the image. (when on image settings)
Attributes:
Name: data-image-target
Value: #my-target-image
And
Name: data-image-url
Value: (image url, in my case Webflow: https://uploads-ssl.webflow.com/something)
These two attributes to each hover element.
Name: id
Value: my-target-image
This to the image element to show images. (if Webflow; "my-target-image" goes in the ID field in element settings.
Here is my mock-up. I'm using react on the website I'm working on, and I just want to add a banner(that is closeable) for every image that is rendered on the website. I'm new to css so I am not sure what class to use, or if I have to make my own, or how usually people implement this kind of mock-up on css.
Background info: I'm doing this because I want to make the website more accessible for the visually impaired. So the description will basically stored as alt text of the image.
The user will be uploading images so they need to be able to add alt-text for the image themselves, not the coder. So I wanted to implement some kind of mechanism for the UI to accept input for every image, and the input is the image description.The problem is I'm not sure how to code that. I need some help where/when to start with.
The ReactJS API can be found here - https://facebook.github.io/react/ (see the An Application Example) There is an example where you can add text to a page dynamically. I would recommened using that same concept. You would have to break the process down in steps.
Step 1: Declare a variable that will capture what is in the text field whenever the user inputs(types/pastes) anything.
Step 2: When the user presses "Add", call that variable with the stored name and apply it as the alt attribute of the image.
Step 3: Use jQuery to add a <div> that is positioned at the bottom of the image and has the same value of the alt attribute of the image.
If you need the actual code please do let me know.
Consider a lightweight, easy to use tool that is dedicated to making everything related to images easier to implement on a webpage (although it can work with other DOM elements as well, i. e., videos, iframes, PDFs).
FancyBox
Here is a simply example of the alt attribute of an image being used to elegantly give the image a title.
Alt Image FancyBox
Lastly, using the same tool, you can use jQuery to build up the alt name and render automatically, so you do not have to do it manually.
// fancyBox v2.0 Next of X Solution, Auto assign title to all images on page.
//www.craigwasselphotoart.com/portrait_and_event_photography/main_test.htm
//http://stackoverflow.com/questions/3216013/get-the-last-item-in-an-array
//All credit goes to JFK of fancybox.net
//Alexander Dixon 07-06-2015
$("a").each(function(index) {
var titleName = $(this).closest("a").find("img").attr("src").toString().split('/').splice(-1, 1);
var anchorIndex = "a:eq(" + index + ")";
$(anchorIndex).attr("title", titleName).attr("rel", "img_gallery");
});
$("a[rel=img_gallery]").fancybox({
helpers: {
title: {
type: 'over'
}
},
// helpers
beforeShow: function() {
this.title = 'Image ' + (this.index + 1) + ' of ' + this.group.length + (this.title ? ' - ' + this.title : '');
} // beforeShow
}); // fancybox
<link href="http://www.alexldixon.com/fancybox/jquery.fancybox.css" rel="stylesheet" />
<script src="http://www.alexldixon.com/fancybox/jquery.fancybox.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="http://fancyapps.com/fancybox/demo/1_b.jpg">
<img src="http://fancyapps.com/fancybox/demo/1_s.jpg" alt="" />
</a>
<a href="http://fancyapps.com/fancybox/demo/2_b.jpg">
<img src="http://fancyapps.com/fancybox/demo/2_s.jpg" alt="" />
</a>
jsFiddle of auto alt Names
I'm working on this site, and I need to change the contents of image_preview, title_preview, description_preview, link_preview according to what I'm hovering over (ex: mouse hover "button_a" = image1.png, iliketitle, ulikedesc, welikelink).
I've tried using css solutions like this and this, but I wasn't able to make them work like I needed.
Since the page will have many button_#'s (50-100 buttons), I think css isn't a proper choice.
So what I'm looking for is a way to do this without css, better if with an xml source file, so it'd be easier to manage the content to display for each button. I only found this talking about the xml I'd need, but I'm not sure that's exactly what I need.
Your buttons have a class (e.g. .btn) and the associated data to each button is store somewhere, let's say each button has a data-* attribute which points to the right data.
$('.btn').hover(function() {
var data = $(this).data('something');
if(data == "b1") {
//assign the values related to b1
}
else if(data == "b2") {
//assign the values related to b2
}
//and so on
}
If you have a lot of buttons like that, then the data can be a reference to an array containing the proper info.
Here's a jsfiddle DEMO.
And here's updated DEMO.
EDIT:
.hover() can take two handler which the second will handle when mouse is out of the element.
yourElement.hover(
function() {
//mouse is on the element, do stuff
},
function() {
//mouse is out, do other stuff
}
);
You can have a function to set the default values and call that in hover's second function.
jsfiddle DEMO
I've just gotten the interest to learn about web programming. Encountered a problem and hope someone could show me some directions.
Example: http://jsfiddle.net/KdhPG/99/
Current: when hover over the image ID, it changes the text ID color to 'red'
Likewise isn't possible to hover over the text ID to change the current img src of the image ID to another image src/URL?
Thanks!
Not good at jQuery.. but here is a possible solution using the hover so that the previous image is restored. The image will change as you say when hovering over the text, once the mouse leaves it will restore the previous image:
var prevsrc;
$("#one").hover(
function() {
prevsrc = $("#img-one").attr('src');
$("#img-one").attr('src', 'yourNewImageUrl');
},
function() {
$("#img-one").attr('src', prevsrc);
}
);
Like this?
http://jsfiddle.net/yDhhr/
That doesn't account for mouseout / unhovering, but you should be able to take this code and do it.
As a side note, using the attr() feature of jQuery you can change basically any attribute you want to. It's pretty useful.
$("#img-one").hover(function() {
$('#img-one').attr("src","http://aviationhumor.net/wp-content/uploads/2011/02/chuck-norris.jpg");
}
EDIT:
As David Thomas mentioned in this case it's better to work with DOM elements like this
this.src = 'http://aviationhumor.net/wp-content/uploads/2011/02/chuck-norris.jpg';
I'm building a photo gallery and what I would like to do is make it so that as the user rolls over an image (let's say for the purposes of this question it's a picture of an apple), all the other images of apples on the page also show their "over" state.
Any and all help would be greatly appreciated, and thank you for your time in advance!
You could add the 'type' of the image as a class. For example an apple will be:
<img src='' class='apple fruit red' />
You can have as many space separated classes as you want.
Then add the following handler:
$(".apple").mouseover(function() {
$(".apple").addClass("overState");
});
You need to define in your CSS the overState. On mouseout you must remove the class.
So each image has a number of tags (eg: "apple", "red", "big"), and when you mouse over the big red apple, you want all other apples, big things and red things to light up?
As kgiannakakis suggested, I'd put that data into the class attribute of the image - the only difference is that I'd prefix each class with something so you don't clash with other classes on your page.
<img src="the-big-red-apple.jpg" class="tagged tag-big tag-red tag-apple" />
I've also added an extra class there called "tagged" so you can tell your tagged photos from navigational images or whatever.
$('img.tagged')
.each(function() {
var thisClasses = this.className.split(/s+/); // array of classes.
var search = [];
for (var i = 0; i < thisClasses.length; ++i) {
if (thisClasses[i].substr(0, 4) == "tag-") {
search.push("." + thisClasses[i]);
}
}
$(this).data("tags", search.join(",")); // ".tag-big,.tag-red,.tag-apple"
})
.hover(function() {
$('img.tagged')
.filter(this.data('tags'))
.addClass("highlight")
;
}, function() {
$('img.tagged')
.filter(this.data('tags'))
.removeClass("highlight")
;
})
;
What this does is initially loop through all your tagged images and work out what the tags are on each of them, storing that into that element's data(). This means we only need to do that once, and not each time.
Then it adds a hover event to each tagged image to find anything which matches any of this image's tags and add the "highlight" class. Similarly it removes the class when you mouseout.
If these are links (anchor tag) you don't need jQuery to do this. You can use :hover in CSS.
a.apple:hover img {
/* whatever you want to change here */
}
EDIT: Ignore me. This won't change all apple elements on the page at the same time. That's what I get for perusing SO late at night when I'm sleepy.
Change the image source
This method would actually change the image sources in a uniform way, rather than just applying a class to them.
function swapImageGroup(imgSelector,suffix){
if (suffix == null) {suffix = "-hover";}
//imgSelector is the jQuery selector to use
//both imgSelector and suffix must be strings
$(selector).hover(
function() {
$(selector).each(function(){
//store ".jpg" or ".png" or whatever as fileExtension
var fileExtension = $(this).attr("src").substr($(this).attr("src").lastIndexOf("."));
//replace something like ".jpg" with something like "-hover.jpg",
//assuming suffix == "-hover"
$(this).attr("src", $(this).attr("src").replace(fileExtension, suffix + fileExtension));
});
},
function() {
$(selector).each(function(){
//chop off the end of the filename, starting at "-hover" (or whatever)
//and put the original extension back on
$(this).attr("src", $(this).attr("src").split(suffix + ".").join("."));
});
}
);
}
So you'd use the function like this:
swapImageGroup("img.apple");
or
swapImageGroup("img.foo","-active");