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>
Related
Here is my code:
$.fn.right = function() {
return $(document).width() - (this.offset().left + this.outerWidth());
}
$(document).ready(function(){
$('a').bind('mouseenter', function() {
var self = $(this);
this.iid = setTimeout(function() {
var tag_name = self.text(),
top = self.position().top + self.outerHeight(true),
right = self.right();
$('body').append("<div class='tag_info'>Some explanations about "+tag_name+"</div>");
$(".tag_info").css({top: top + "px", right: right + "px"}).fadeIn(200);
}, 525);
}).bind('mouseleave', function(){
if(this.iid){
clearTimeout(this.iid)
$('.tag_info').remove();
}
});
});
body{
padding: 20px;
direction: rtl;
}
a {
color: #3e6d8e !important;
background-color: #E1ECF4;
padding: 2px 5px;
}
.tag_info{
position: absolute;
width: 130px;
height: 100px;
display:none;
background-color: black;
color: white;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a>long-length-tag</a>
<a>tag</a>
It works fine. But in reality, the content (those tags) will be created later. I mean they will be created as an ajax response. So $('a') doesn't select them.
Now I'v written it like $(document).bind('mouseenter', 'a', function(){ ... }) to make that working even for the DOM which is created after page loading.
But as you see in this fiddle, it doesn't work. Does anybody know what's the problem and how can I fix it?
You need to bind the event with .on(). This works for future elements as well.
$(document).on('mouseenter', 'a', function(){ ... });
And, as #Gregg has answered, .bind() has been replaced by .on(). That's the actual cause why your fiddle doesn't work.
The on() function has replaced bind() since jQuery 1.7. If you read the documentation, you'll note that live() was actually used for delegate events like what you're trying to achieve while the bind() method was not; binding events to elements that will be added to the DOM later. The on() function can do this. Either from the document itself or from a direct descendent.
When anchor tag are being created in response of your AJAX call, put id in it like this:
$('body').append("<div class='tag_info' id='myTag'>Some explanations about "+tag_name+"</div>");
and then you can bind event mouseenter or mouseleave like this:
$('#myTag').bind('mouseenter', function(){
alert('Mouse Enter in your Anchor Tag');
}).bind('mouseleave', function(){
alert('Mouse leave');
});
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');
}
});
For the HTML below, what is the best centralized way to replace using an inline onclick in each of the five siblings's children DIVs to set the background color red for whichever one gets clicked and clearing all others?
The inline approach to be replaced:
<div id="tab1" onclick="setRed();">tab 1</div>
Leaving cleaner markup:
<div>tab 1</div>
This is how the whole thing should look:
<div id="nav">
<div class="blue"><div>tab 1</div></div>
<div class="blue"><div>tab 2</div></div>
<div class="blue"><div>tab 3</div></div>
<div class="blue"><div>tab 4</div></div>
<div class="blue"><div>tab 5</div></div>
</div>
This is the final solution, hobbling the select portion from user2865156 and adding some javascript to clear the rest:
$("#nav div div").on('click', function () {
if (this.style.backgroundColor !== "red") {
this.style.backgroundColor = "red";
siblingDivs = this.parentNode.parentNode.children;
for (var i = 0; i < siblingDivs.length; i++) {
if (this !== siblingDivs[i].children[0]) {
siblingDivs[i].children[0].style.backgroundColor = "transparent";
}
}
}
});
Try using something like this. You need to set it to the actual function instead of the value of the return value:
var divTabs = document.getElementById("nav").onclick = function() {
//do something here
}
If I understood your question, you may need to use the .each() method to get the index of the clicked element and add the corresponding red class to it, so
having this css
.red { background-color: #ff0000; }
You could use this jQuery script:
jQuery(document).ready(function ($) {
$(".blue").each(function (i) {
$(this).on("click", function () {
$(".blue").removeClass("red").eq(i).addClass("red")
})
})
}); // ready
Notice we are using the .eq(i) method to assign the red class to the clicked element after removing the same class from any other.
See JSFIDDLE
I think this is what you need.
DEMO
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
padding: 24px;
}
.blue {
cursor: default;
border: 1px dashed #454545;
padding: 8px 16px;
display: inline-block;
}
.blue.active {
background: red;
}
jquery js
$(function() {
$('#nav').on('click', '.blue', function(e) {
var $this = $(this),
innerHtml = $this.html(), //inner html
text = $this.text();
// there are obv easier ways to do the below; just a proof of concept.
!!~text.indexOf("tab") && $('.active').removeClass('active') &&
$this.addClass('active');
})
})
Using jQuery, target the class:
$("#nav .blue").click(function() {
//$(this) refers to the clicked element as a jQuery object
var innerHtml = $(this).html(); //inner html
var text = $(this).text(); //text inside the inner html
//Logic
});
Is this what you're trying to do?
http://jsfiddle.net/Lwex5wr4/
$(".blue").on('click', function() {
if (this.style.backgroundColor === "red") {
this.style.backgroundColor = "transparent";
} else {
this.style.backgroundColor = "red";
}
});
Try to do this:
$("#nav .blue").click(function() {
$(this).css('background-color', 'red');
});
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');
});
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 */
}