I'm trying to change a div background image on hover, I want to do this with JaveScript so that it works cross browser without any issues. The current code I have is:
<div class="staff" style="background-image: url(/wp-content/uploads/2013/08/IMG_1828- 300x237.png);" onmouseover="this.style.background=url(wp-content/uploads/2013/08/IMG_1836-v2-300x237.png);" onmouseout="this.style.background=url(wp-content/uploads/2013/08/IMG_1828-300x237.png);">
</div>
CSS:
.staff{
width: 300px;
height: 237px;
}
Can anybody see what is causing the problem?
<style>
.staff{
width: 300px;
height: 237px;
background-image: url(/wp-content/uploads/2013/08/IMG_1828- 300x237.png);
}
.staff:hover {
background-image: url(wp-content/uploads/2013/08/IMG_1836-v2-300x237.png);
}
</style>
<div class="staff"></div>
You can use simple css too.. and it will work on all browsers
.staff { background: url("url/img.png")}
.staff:hover { background: url("url/hoverimg.png")}
<div class="staff"></div>
Better use CSS than inline CSS and javascript to achieve the effect.
If you still want to do it inline, here is a example.
jsfiddle
onmouseover="javascript: this.style.backgroundImage = 'url(\'image_url\')'";
you can use css like this:
.staff{
width: 300px;
height: 237px;
background-image: url("/wp-content/uploads/2013/08/IMG_1828- 300x237.png");
}
.staff:hover{
background-image: url("wp-content/uploads/2013/08/IMG_1836-v2-300x237.png");
}
or javascript like:
onmouseover="javascript: this.style.backgroundImage = 'url(\'image_url\')'";
WORKING DEMO
CHANGE I MADE
onmouseover="this.style.background='url()';"
You have to enclose the url in single qoutes...
I would also suggest you use CSS rather than JS to do this. But since you asked how to do it in JS, this is your answer
Most browser should support :hover in css, so there is no need to use JavaScript for this (relevant fiddle here):
.staff{
width: 300px;
height: 237px;
background-image: url("/wp-content/uploads/2013/08/IMG_1828- 300x237.png");
}
.staff:hover{
background-image: url("wp-content/uploads/2013/08/IMG_1836-v2-300x237.png");
}
If you really want to use JavaScript, than you have to wrap url(...) in quotes like so:
<div class="staff"
style="background-image: url(/wp-content/uploads/2013/08/IMG_1828- 300x237.png);"
onmouseover="this.style.background='url(wp-content/uploads/2013/08/IMG_1836-v2-300x237.png)';"
onmouseout="this.style.background='url(wp-content/uploads/2013/08/IMG_1828-300x237.png);'">
</div>
I think you can use this script :
$('.staff').mouseover(function() {
$(this).attr('style',"background:grey;");
})
$('.staff').mouseout(function() {
$(this).attr('style',"background:white;");
})
Change the color to the image path.
$(document).ready(function(){
var staff = $(".staff"); //Avoid repeated traverse
$("img").hover(function(){
staff.css("background",'url(' + $(this).attr('src') + ')');
//Assuming you want to set current image as background image
});
$( "img" ).mouseout(function(){
staff.css("background","none");
});
});
Okay this works for me so when you hover over an image the background of the set div is changed. So when ever you hover over an image .staff background is changed.
I believe that is what you want?
Related
I am currently trying to add a custom JS function (via the Live Code Editor Plugin) to my wordpress website. The goal is to change the background colour of a toggle after click (i.e. from red -> green). I have tried this function but although the selector works for CSS, the JS function is not working:
CSS:
\23 toggle-id-1 {
background-color: red;
}
JS:
var \23 toggle-id-1 = document.getElementById("\23 toggle-id-1");
\23 toggle-id-1.onclick = function(){
\23 toggle-id-1.style.backgroundColor = "green";
}
In JSFiddle this worked without any problems, is there anything different for this plugin?
Thank you!
jQuery solution:
$("#toggle-id-1").click(function () {
$(this).toggleClass("green");
});
#toggle-id-1 {
background-color: red;
height: 100px;
width: 100px;
}
#toggle-id-1.green { background-color: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="toggle-id-1" class=""></div>
You can't have spaces in variable names. Name your variable something else.
I'm trying to swap background using jQuery. But the problem is that it doesn't successfully switch to new background, instead, the old one is removed and I get a white background instead.
I've been googling and trying out putting the path as a var instead for example, and some other unsuccessful suggestions.
My jQuery function looks like the following:
$("#btn").hover(function () {
$('#page1').css('background-image','url(../images/bg1_normal.jpg)');
});
And my CSS for the default background looks like this:
#page1 {
height: 100vh;
max-height: 100vh;
background-image: url("../images/bg1_rw.jpg");
background-repeat: no-repeat;
background-size: 100%;
}
I'm using Java Play Framework and the pictures are in the same folder, and it is the correct path to it since the default background works.
EDIT: I Tried as well to use an img source from the web, just to be 100% sure it wasn't some issues with the path, but it still only makes it white.
I believe jQuery's hover() function isn't able to remove that particular style when the mouse leaves.
You could just do it yourself
$("#btn").on({
mouseenter : function() {
$('#page1').css('background-image','url(../images/bg1_normal.jpg)');
},
mouseleave : function() {
$('#page1').removeAttr('style');
// or simply set the backround again to the other image
}
});
Try .addClass and .removeClass functions - it's simple and all style work is done in stylesheet file:
$("#btn").on({
mouseenter : function() {
$('#page1').addClass('inverted');
},
mouseleave : function() {
$('#page1').removeClass('inverted');
}
});
and then simply add
#page1.inverted {
//style as you need
}
to your stylesheet.
If you're using images you could do an image swap like this
https://jsfiddle.net/RachGal/oee3guxz/
$("#flowers").mouseover(function () {
var _this = $(this);
var current = _this.attr("src");
var swap = _this.attr("data-swap");
_this.attr('src', swap).attr("data-swap", current);
_this.toggleClass("opaque");
});
.opaque {
opacity:.5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<img id='flowers' class="full" src='http://www.rachelgallen.com/images/snowdrops.jpg' width="500" height="400" data-swap='http://www.rachelgallen.com/images/daisies.jpg' width="500" height="400" />
or if you could just use color like this
$("#color").mouseleave(function () {
$("body").css("background-color","black");
});
$("#color").mouseover(function (){
$("body").css("background-color","red");
});
$("#color").click(function(){
$("body").css("background-color","green");
});
body, #color {
height: 800px;
width: 800px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="color"> </div>
https://jsfiddle.net/RachGal/8p783jfo/
Hope this helps
Rach
When I click on it changes background. It works fine. But what if I want to click on it again to restore the original background? I have this code:
jQuery(document).ready(function($) {
$(".select").on("click", function () {
$(this).css("background-image", "url(images/selected.png)");
});
});
Here is jsfiddle EXAMPLE
Basically when I click on the div it changes the background, which is fine. But I want to have ability to click on it again to restore the original background.
It will be an alternative solution for tick box, but just for demo purposes.
Thanks
JS
replace
$(this).css("background-image", "url(images/selected.png)");
with
$(this).toggleClass("active");
Style
#multiselect .active {
background-image: url('...');
}
Fiddle http://jsfiddle.net/09xgrhxo/4/
Instead of using .css() to change the background-image I would add a class in your CSS and use .toggleClass().
Also be aware that simply adding a class will not be specific enough because your css is using:
#multiselect .select
you're going to have to target the class you add as a child of #multiselect:
#multiselect .change
CSS
#multiselect .change{
background-image: url(http://t2.gstatic.com/images?q=tbn:ANd9GcSZ51HqKXkejWAFcSBrodHd5eUN2QaIJro0jhN1YpmljSdQ5dj2)
}
JS
$(".select").on("click", function () {
$(this).toggleClass("change");
});
FIDDLE
You could use data-* attribute.
$('.select').attr('data-img', $('.select').css('background-image'));
$(".select").on("click", function() {
$(this).css("background-image", ($(this).css('background-image') == $(this).data('img')) ? "url(http://t2.gstatic.com/images?q=tbn:ANd9GcSZ51HqKXkejWAFcSBrodHd5eUN2QaIJro0jhN1YpmljSdQ5dj2)" : $(this).data('img'));
});
#multiselect .select {
background: url(http://t0.gstatic.com/images?q=tbn:ANd9GcQF_ErOlc78eOGZaEWb-dwPkrv2uyAoKx0Pbn3-e0tAZoUDSQRCsA) center;
width: 250px;
height: 100px;
margin-bottom: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="multiselect">
<div class="select">Option1</div>
<div class="select">Option2</div>
<div class="select">Option3</div>
</div>
Instead of writing background-img url in javascrpt, I would suggest to create two classes having same properties but different background-img url which you want to toggle. so here we will be toggling class (ultimately background-img) in javascript.
see jsfiddle [example][1]
[1]: http://jsfiddle.net/09xgrhxo/13/
The code is pretty simple.
HTML:
<div class="simpleDiv" id="Child1" onmouseover="expandDiv(this);"></div>
CSS:
.simpleDiv {
background-color: red;
width: 100px;
height: 50px;
margin: 5px;
margin-left: 50px;
opacity: 1;
}
JavaScript:
function expandDiv(object){
alert(document.getElementById(object.id).style.height);
}
Why am I not able to alert the height of the div like this? If I alert the id or class using the function hasAttribute, thats working fine but not able to alert the css properties of the elements.
Any help appreciated!
Why not just alert(object.style.height)?
Anyway, the reason it doesn't work is because elem.style.property only works with inline style="..." attributes. To take into account all styles, you need this:
alert(window.getComputedStyle(object).height)
Older versions of IE don't support this, but it's a very easy shim:
window.getComputedStyle = window.getComputedStyle || function(e) {return e.currentStyle;};
function expandDiv(object){
alert(document.getElementById(object.id).innerHeight);
}
try using:
alert(document.getElementById(object.id).offsetHeight);
Here is description:
offsetHeight on MDN
Use JQuery:
alert($('#Child1').css("height");
Or to change the attribute, use:
$('#Child1').css("height", value )
Ignore if you don't want JQuery.
I want to drop the opacity and overlay text on a thumbnail image when I mouse over it. I have several ideas about how to do it, but I'm fairly certain they're inefficient and clumsy.
Make a duplicate image in Photoshop with the text overlay and reduced opacity. Swap the original out for the duplicate on mouseover.
Use CSS to drop the opacity on mouseover. Use Javascript to toggle visibility of a div containing the overlay text.
The problem I see with 1 is it seems like an unnecessary use of space and bandwidth, and will cause slow load times. With 2, it seems like I'd have to hard-code in the location of each div, which would be a pain to maintain and update. I know this is a somewhat general question, but I'm at a loss about how to go about this. How can I do this relatively simple task in a way that will make it easy to add new thumbnails?
Wrap your image in a <div class="thumb">
Add position: relative to .thumb.
Add <div class="text> inside .thumb.
Add display: none; position: absolute; bottom: 0 to .text.
Use .thumb:hover .text { display: block } to make the text visible on hover.
Like this: http://jsfiddle.net/dYxYs/
You could enhance this with some JavaScript/jQuery: http://jsfiddle.net/dYxYs/1/
$('.text').hide().removeClass('text').addClass('text-js');
$('.thumb').hover(function(){
$(this).find('.text-js').fadeToggle();
});
This way, the basic effect still works without JavaScript, and users with JavaScript get the appealing fade effect.
Go with option 2. There are ways to do it to not have to write a jQuery function for each image. As seen in my jsfiddle.
http://jsfiddle.net/daybreaker/dfJHZ/
HTML
<img src="http://placekitten.com/300/300" />
<span class="text" style="display:none">THIS IS A KITTEN</span>
<br><br>
<img src="http://placekitten.com/200/200" />
<span class="text" style="display:none">THIS IS A KITTEN</span>
jQuery
$('img').mouseover(function(){
$(this).css('opacity','.2');
$(this).next('span.text').show();
}).mouseout(function(){
$(this).css('opacity','1');
$(this).next('span.text').hide();
});
You would need to modify the span.text css to overlay it on top of the image, but that shouldnt be too bad.
Wrap it in an element and do something like this:
var t;
$('div.imgwrap img').hover(function(){
t = $('<div />').text($(this).attr('title')).appendTo($(this).parent());
$(this).fadeTo('fast',0.5);
},function(){
$(this).fadeTo('fast',1);
$(t).remove();
});
with a markup similar to:
<div class="imgwrap">
<img src="http://www.gravatar.com/avatar/3d561d41394ff0d5d0715b2695c3dcf0?s=128&d=identicon&r=PG" title="text" />
</div>
example: http://jsfiddle.net/niklasvh/Wtr9W/
Here's an example. You can position the text however you want, but the basic principle below.
http://jsfiddle.net/Xrvha/
#container { position: relative; }
#container img, #container div {
position: absolute;
width: 128px;
height: 128px;
}
#container img { z-index -1; }
#container div {
z-index 1;
line-height: 128px;
opacity: 0;
text-align: center;
}
#container:hover img {
opacity: 0.35;
}
#container:hover div {
opacity: 1;
}
If you don't want to change your HTML wraping things etc, I suggest you this way. Here is the jQuery:
$(function() {
$(".thumb").mouseenter(function() {
var $t = $(this);
var $d = $("<div>");
$d.addClass("desc").text($t.attr("alt")).css({
width: $t.width(),
height: $t.height() - 20,
top: $t.position().top
});
$t.after($d).fadeTo("fast", 0.3);
$d.mouseleave(function() {
$(this).fadeOut("fast", 0, function() {
$(this).remove();
}).siblings("img.thumb").fadeTo("fast", 1.0);
});
});
});
2 is a good solution, have done about the same as this and it isn't as hard as you would've tought;
Drop de opacity with css indeed, than position a div relative to the img, and over it. It can be done with plain css. The z-index is the trick. That div can just be shown with $('#div').slideUp() ie.