Jquery, changing color on hover - javascript

This has been driving me crazy for a while, I cannot figure out what I am doing wrong. I am trying to make a 4x4 grid and change the color of each square when I hover my mouse over (the color stays after the mouse leaves) but the changing color part is not working.
Here is what I have so far:
Changing color on hover:
This is the part where I am stuck
$('.square').hover(function () {
$(this).addClass('hover');
});

You can remove your jquery code for adding class hover and just make this css change in the file
.square:hover {
background-color: red;
}
simply fixes your problem in pure Css.
Adding JsFiddle for this
http://jsfiddle.net/jjeswin/nb3dB/1/

You need to first call makeGrid(4); and then bind the event.
also to remove class you need to modify hover function to use mouseenter and mouseleave function:
makeGrid(4);
$('.square').hover(function() {
$(this).addClass('hover');
},function() {
$(this).removeClass('hover');
});
Working Demo
Update: for keeping the color even after mouseleave:
makeGrid(4);
makeGrid(4);
$('.square').hover(function() {
$(this).addClass('hover');
});
Demo with only mouseenter

I have updated the fiddle code http://jsfiddle.net/ZfKM8/5/
In your javascript, i've removed the hover function.
$(document).ready(function() {
function makeGrid(n) {
var grid = $('#container');
for (var i = 1;i<=n; i++) {
for (var j = 1; j <= n; j++){
grid.append("<div class='square'></div>");
}
grid.append("<div class='new_row'></div>");
}
};
makeGrid(4);
});
in your css, instead of .hover change it to .square:hover
.square:hover {
background-color: red;
}

$('#container').on("mouseenter", '.square', function() {
$(this).addClass('hover');
});
$('#container').on("mouseleave", '.square', function() {
$(this).removeClass('hover');
});
Use event delegation for dynamically created elements.
Demo:
http://jsfiddle.net/m6Bnz/1/

Use event delegation for added dom elements dynamically . it is the best way to do
$('#container').on('mouseenter' , ".square" , function() {
$(this).addClass('hover');
});
/* $('#container').on('mouseleave' , ".square" , function() {
$(this).removeClass('hover');
}); */
DEMO

here you go: http://jsfiddle.net/ZfKM8/3/
$(document).ready(function() {
function makeGrid(n) {
var grid = $('#container');
for (var i = 1;i<=n; i++) {
for (var j = 1; j <= n; j++){
grid.append("<div class='square'></div>");
}
grid.append("<div class='new_row'></div>");
}
};
makeGrid(4);
$(document).on('mouseenter','.square',function() {
$(this).addClass('hover');
});
$(document).on('mouseleave','.square',function() {
$(this).removeClass('hover');
});
});

Is there a specific reason why you're not using CSS for this?
.square:hover { color: #superAwesome }
If you want the color to animate (and delay when mousing out) you can use CSS3 transition:
.square { transition: color 1s; }

Try this
<html>
<head>
<script src="js/jquery.min.js"></script>
<script src="js/jquery-ui.min.js"></script>
<style>
.hover
{
background:red;
}
</style>
</head>
<body>
<div class="square" style="width:100px;height:100px;border:1px solid"> </div>
<script type="text/javascript">
$('.square').hover(function()
{
$(this).addClass('hover');
});
$('.square').mouseout(function()
{
$(this).removeClass('hover');
});
</script>
</body>
</html>

Since your boxes created dynamically to the DOM, the hover event will not be available for these boxes. In this case, event delegation will help you to attach that event
Try this
OP said the color stays after the mouse leaves
$('#container').on('mouseenter','.square',function() {
$(this).addClass('hover');
});

Make use of .toggleClass():
makeGrid(4);
$('.square').hover(function() {
$(this).toggleClass('hover');
});

Related

Why won't my jQuery code run?

First off, I apologize for the extremely elementary question. I am a complete newbie and have been teaching myself without any outside help. Be gentle.
I am completing an exercise from a free web dev course, and one of the steps is to add background color to some divs using jQuery. I have used both .hover and .mouseover methods, but neither are working. If I put the code outside of the $(document).ready brackets, nothing happens. If I put the code inside of it, all of my work looks like it's erased.
Here's the code:
$(".pixel").hover(function(){
$(this).css("background-color", "yellow");
}, function() {
$(this).css("background-color", "red");
});
Inside the $(document).ready function I created lots of divs with class="pixel", so I figured I should be able to select them using the above code.
Edit:
Again, I am sorry it seems I'm not including enough information. This is literally my first attempt at posting something here. I have nobody I can ask these questions to.
Here is the beginning of my .js file, before the .hover code I'm trying to run:
$(document).ready(function() {
$("body").append("<div id='main'>");
for (var i=0; i<256; i++) {
$("#main").append("<div class='pixel'></div>");
};
$(".pixel").last().append("</div>");
});
Two options - you can either initialize your hover event after creating the elements, or even better, you can use jQuery .on('mouseover') and .on('mouseout') and initialize the event before the elements are created:
$(document).on("mouseover", ".pixel", function() {
$(this).css("background-color", "yellow");
}).on("mouseout", ".pixel", function() {
$(this).css("background-color", "red");
});
$("body").append("<div id='main'>");
for (var i = 0; i < 256; i++) {
$("#main").append("<div class='pixel'></div>");
};
.pixel {
border: 1px solid #000;
display: inline-block;
width: 10px;
height: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Or, the version still using the shorthand hover:
$("body").append("<div id='main'>");
for (var i = 0; i < 256; i++) {
$("#main").append("<div class='pixel'></div>");
};
$(".pixel").hover(function() {
$(this).css("background-color", "yellow");
}, function() {
$(this).css("background-color", "red");
});
.pixel {
border: 1px solid #000;
display: inline-block;
width: 10px;
height: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The issue is that you're appending the element you're trying to hover. Because it's not part of the DOM on page load, the event binding won't work the way you have it. Instead use:
$(document).ready(function(){
$("body").append("<div id='main'>");
for(var i=0; i<256; i++) {
$("#main").append("<div class='pixel'>Pixel</div>");
};
$(".pixel").last().append("</div>");
});
// Change BG on hover
$(document).on({
mouseenter: function(){
$(this).css("background-color", "yellow");
},
mouseleave: function(){
$(this).css("background-color", "red");
}
}, '.pixel');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

How to handle class (made by jQuery) with jQuery?

I'm new in jQuery. This time I tried to make a double-stage effect using jQuery.
For example, when you click the word, its color changed to red at first. And when you clicked it again, its color changed to blue.
So I used following code, but it doesn't work well.
$(document).ready(function () {
$("p#origin").click(function () {
$(this).css("color", "red");
$(this).addClass("clicked");
});
$("p.clicked").click(function () {
$(this).css("color", "blue");
});
});
You can see the result at here
I also tried this.
var toggle = 0;
console.log("toggle", toggle);
$(document).ready(function () {
if (toggle == 0) {
$("p#origin").click(function () {
$(this).css("color", "red");
toggle = 1;
console.log("toggle:", toggle);
});
} else {
$("p#origin").click(function () {
$(this).css("color", "blue");
toggle = 0;
console.log("toggle", toggle);
});
}
});
Above code result can be seen here. The variable toggle is set to 1, but it doesn't work.
Is my question delivered well...? I'm new here, so I don't know how the javascript code loaded. (I also need help to study about this...)
I hope any solution to make a double stage effect. (Could anyone fix my above 2 codes to work well?)
The problem is you are dealing with dynamic selectors, ie you want the events handled to change based on dynamic evaluation of the selector, in that case you need to use event delegation.
But in this case you don't need that, assuming at first the p#origin does not have blue color you can do something like
$(document).ready(function() {
$("p#origin").click(function() {
$(this).toggleClass("clicked").toggleClass('unclicked', !$(this).hasClass('clicked'));
});
});
#origin.unclicked {
color: blue;
}
#origin.clicked {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="origin">origin</p>
But if p#origin has blue color before the first click, then you can simplify it to
$(document).ready(function() {
$("p#origin").click(function() {
$(this).toggleClass("clicked");
});
});
#origin {
color: blue;
}
#origin.clicked {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="origin">origin</p>
Just an idea instead of using .class:
Loop an array of styles (you can use as many styles/steps you want)
var c = ["#000", "#f00", "blue"];
$("#origin").click(function(){
c.push(c.shift()); // Put first array color to last place
$(this).css({color: c[0] }); // Always use the 0 key
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="origin">Click to Toggle Color</p>
If you want to change more than just a color:
var c = [
{color:"#000", background:"#ffe", fontSize:16},
{color:"fuchsia", background:"yellow", fontSize:24},
{color:"#1CEA6E", background:"#C0FFEE", fontSize:36}
];
$("#origin").click(function(){
c.push(c.shift());
$(this).css(c[0]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="origin">Click to loop styles</p>
I just modified some JavaScript code from you, simply.
var $origin;
$origin = $('#origin');
return $origin.on('click', function() {
if ($origin.hasClass('red')) {
$origin.css('color', 'yellow');
$origin.addClass('yellow');
return $origin.removeClass('red');
} else {
$origin.css('color', 'red');
$origin.addClass('red');
return $origin.removeClass('yellow');
}
});

what is the best way to return the orginal style when mouseleave jquery?

I use mouseenter to input a new html. I face a challenge that I need to return the original style when mouse leave? When mouseleave, I need to remove the new html and use the original html What is the best way to do that?
var eye_disease1 = $('#eye_disease1');
eye_disease1.mouseenter(function () {
eye_disease1.html('<span class="show_li">symptoms</span><span class="show_li_2">diseases</span>').hide().fadeIn();
eye_disease1.css('border', 'none');
}).mouseleave(function () {
// what should I put here to return the original
});
Get the original HTML of eye_disease1 before changing and after mouse leave update HTML.
var eye_disease1 = $('#eye_disease1'),
diseaseHtml = '';
eye_disease1.mouseenter(function () {
if (!diseaseHtml) {
diseaseHtml = eye_disease1.html();
}
eye_disease1.html('<span class="show_li">symptoms</span><span class="show_li_2">diseases</span>').hide().fadeIn();
eye_disease1.css('border', 'none');
}).mouseleave(function () {
diseaseHtml = '';
eye_disease1.html(diseaseHtml);
});
You can all use the addClass
`$("selector").mouseenter(function(){
$(this).addClass("active");
})
$("selector").mouseleave(function(){
$(this).removeClass("active");
})`
var eye_disease1=$('#eye_disease1');
var eye_disease1_html;
eye_disease1.hover(
function() {
eye_disease_1_html = eye_disease1.html();
eye_disease1.html('<span class="show_li">symptoms</span><span class="show_li_2">diseases</span>')
.fadeOut(0)
.css('border','none')
.fadeIn(400);
}, function() {
eye_disease1.find('span.show_li, span.show_li_2')
.fadeOut(400)
.delay(400)
.html(eye_disease1_html)
.fadeIn(0);
}
);
But yeah I would prefer to have all the content inside (original, and the hovered content) there the whole time.
HTML:
<div id="eye_disease1">
<div class="original-content">
Original Content
</div>
<div class="hovered-content">
<span class="show_li">symptoms</span>
<span class="show_li_2">diseases</span>
</div>
</div>
CSS:
.hovered-content {
display: none;
}
.hovered {
border: none;
}
JS:
$('#eye_disease1').hover(
function() {
$(this).addClass("hovered");
$(this).find(".original-content").fadeOut();
$(this).find(".hovered-content").fadeIn();
}, function() {
$(this).removeClass("hovered");
$(this).find(".hovered-content").fadeOut();
$(this).find(".original-content").fadeIn();
}
);
You can see it here: https://jsfiddle.net/waga7Lu1/3/
The transition effect is a bit clumsy but I'm not really sure what you're after.

mouseenter mouseleave within contents of iframe

I'm trying to highlight elements within a iframe with no success. I've tried using mouseenter/mouseleave with no success. It does not fire.
$('#iframe').contents().mouseenter(function (e) {
//var element = $(e.target);
var element = $(this);
$(element).addClass("highlight");
}).mouseleave(function (e) {
$(element).removeClass("highlight");
});
I've had better success with mousemove however it highlights the parents as well which I don't want.
var prevElement;
$('#iframe').contents().find('html').on('mousedown', function (e) {
e.stoppropagation()
//e.preventDefault - did not work either
var element = $(e.target);
if (prevElement == null) {
prevElement = element;
element.addClass("edit-element-selector");
}
else {
if (prevElement != element) {
prevElement.removeClass("highlight");
//prevElement.parents().removeClass("highlight"); did not work
element.addClass("highlight");
}
}
});
HTML
<iframe id="iframe" srcdoc="#Html.Raw(ViewBag.html)"></iframe>
The css rule for .hover is not visible in the context of the iframe.
Either use .css() to set style directly, add the css links or clone all styles in the main document into the iframe with jQuery.
Here is a working jfiddle which you should easily be able to copy.
http://jsfiddle.net/danmana/pMBw2/
My problem had 2 issues.
My css was wrong.
Wrong
.highlight :hover {
outline:4px solid #f00;
}
Right
.highlight {
outline:4px solid #f00;
}
Hover was bubbling up to the parents. Mouseenter and mouseleave worked however.
var $iframe = $("#iframe").contents();
$iframe.find('*').mouseover(function (e) {
$(e.target).addClass('highlight');
}).mouseout(function (e) {
$(e.target).removeClass('highlight');
});
Try jQuery Hover
$(function () {
var iContent = $('#iframe').contents();
iContent.find('#id_username').val("New Value!");
iContent.find('#id_username').hover(function () {
$(this).css("border", "1px solid red");
}, function () {
$(this).css("border", "1px solid #c4c7cb");
});
console.log(iContent.find('#id_username'));
});
jsFiddle
Sorry I guess I misunderstood the question. Here is an updated fiddle changing the value of a text input and changing border color on hover.

Javascript Div rollovers

I am using Jquery - is there a simple way to change the background color on a div when a user rolls over it?
You can do this with CSS:
#myDiv:hover { background-color: red; }
//or...
div:hover { background-color: red; }
If you need IE6 support and such and have to use jQuery, toggle a class, like this:
.hover { background-color: red; }
Then use .hover() and .toggleClass(), like this:
$(".myDivs").hover(function() {
$(this).toggleClass('hover');
});
You could use the .hover() event:
$('#divid').hover(function() {
// mouse enter
$(this).css('background-color', 'red');
}, function() {
// mouse leave
$(this).css('background-color', 'blue');
});
I think mouseenter & mouseleave is better than hover. Why? Bubbling reason ;)
if($.browser.msie && $.browser.version < 7) {
$('element').bind({
mouseenter:function(){ $(this).addClass('over'); },
mouseleave:function(){ $(this).removeClass('over');}
});
}
After this, you can simply add some CSS magic:
#element.over,
#element:hover {
/* do something */
}

Categories

Resources