jQuery action on each single element with multiple instances - javascript

Say I have 5 divs, all having the same styling:
Fiddle
HTML
<div id="box"> </div>
<div id="box"> </div>
<div id="box"> </div>
<div id="box"> </div>
<div id="box"> </div>
CSS
#box {
background-color:blue;
width:200px;
height:50px;
display:block;
margin-top:10px;
}
I want to execute some jQuery in order to change the colour of every specific div on .mouseover(), and change it back to the original on .mouseout():
jQuery
$(document).ready(function() {
$('#box').mouseover(function() {
$('#box').css('background-color', 'red');
});
$('#box').mouseout(function() {
$('#box').css('background-color', 'blue');
});
});
This only works for the first instance of the div, how would I go about making this work for every individual one? I want each div to work as it's own but I have no idea how to do that.
I researched and found out about .each() but I'm clueless as to how to incorporate that into my function. Can someone please help me out? Thank you in advance.

ID must be Unique.
You can use the same class to all the elements. There is no need of using Javascript when you can use :hover in CSS to change the style of element on hover.
Updated Fiddle
.box {
background-color: blue;
width: 200px;
height: 50px;
display: block;
margin-top: 10px;
}
.box:hover {
background: red;
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>

As people said ID must be always unique and along with that if you want to achieve it jquery way, then you can do it as below:
$(document).ready(function() {
//bind class element with '.' prefixed
$('.box').mouseover(function() {
$(this).css('background-color', 'red');
//$(this) refers to current element here
});
$('.box').mouseout(function() {
$(this).css('background-color', 'blue');
});
});
.box {
background-color: blue;
width: 200px;
height: 50px;
display: block;
margin-top: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
UPDATE
Using hover and with some performance improving aspect you can try to achieve it as below:
$(document).ready(function() {
$('.box').hover(function() {
$(this).css('background-color', 'red');
},function(){
$(this).css('background-color', 'blue');
});
});

You can't look for objects with same id, instead, you can use .each jquery function to look out for each div with id #box.
It looks like in this fiddle.
Fiddle
$(document).ready(function() {
$( "div#box" ).each(function() {
$( this ).mouseover(function(index) {
console.log( index + ": " + $( this ).text() );
$(this).css('background-color', 'red');
});
$( this ).mouseout(function(index) {
console.log( index + ": " + $( this ).text() );
$(this).css('background-color', 'blue');
});
});
});

Related

Toggle between display of 2 divs

I am trying to learn jquery and I have 2 div elements that I want only with one button to toggle between hide and show. I tried to write everything that I want but I think the sintax is wrong.
<div id="first"></div>
<div id="second">
</div>
<button class="change">change</button>
CSS:
#first {
width:500px;
height:500px;
margin:0 auto;
background-color:#ccc;
}
#second {
width:500px;
height:500px;
margin:0 auto;
background-color:black;
display:none;
}
and I wrote as Jquery
$(document).ready(function() {
$('.change').click(function() {
$('#first').hide();
$('#second').show();
});
});
I was thinking about an if else statement however I am not sure if can handle that yet.
You can use toggle method of jQuery. Make your second div hidden on initialisation...
$(document).ready(function() {
$('.change').click(function() {
$('#first, #second').toggle();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="first">first</div>
<div id="second" style="display: none;">second</div>
<button class="change">change</button>
working example: https://jsfiddle.net/tanaydin/kjyq0eow/3/
documentation: http://api.jquery.com/toggle/
edited after: #Darren Sweeney's comment, much better with this selector.
First thing, you won't see emptys divs.
Example - 1
$(document).ready(function() {
$('.change').click(function() {
$('#first').toggle();
$('#second').toggle();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="first" style="display: none">teste</div>
<div id="second">teste2</div>
<button class="change">change</button>
Example - 2
You can check if a element is visible with that:
$(document).ready(function() {
$('.change').click(function() {
if($('#first').is(":visible")){
$('#first').hide();
$('#second').show();
}else{
$('#first').show();
$('#second').hide();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="first">test1</div>
<div id="second">test2</div>
<button class="change">change</button>

change div1 on hover over div2 which is under div1

Is it possible to change div1 if div2 is hovered but under div1?
/* Works */
.div1:hover + .div2 {
background-color: red;
}
/* Doesn't Work */
.div2:hover + .div1,
.div2:hover ~ .div1,
.div2:hover .div1 {
background-color: red;
}
<div class="div1">hover</div>
<div class="div2">hover</div>
Solutions using Javascript and/or JQuery are also appreciated
Using JQuery's .hover() + .css() for both the divs
$( ".div1" ).hover(
function() {
$(".div2").css( "background-color", "red" );
}, function() {
$(".div2").css( "background-color", "initial" );
}
);
$( ".div2" ).hover(
function() {
$(".div1").css( "background-color", "red" );
}, function() {
$(".div1").css( "background-color", "initial" );
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div1">hover</div>
<div class="div2">hover</div>
If you don't want to use javascript, you can use display: flex on the container, then change the rendering order (note that the html order has to be updated as well). Then you can hover on div2 and highlight div1.
.container {
display: flex;
flex-wrap: wrap;
}
.div1, .div2 {
flex: 0 0 100%;
}
.div1 { order: 1; }
.div2 { order: 2; }
.div2:hover ~ .div1 {
background-color: red;
}
<div class="container">
<div class="div2">hover 2</div>
<div class="div1">hover 1</div>
</div>
Nope, the CSS does not provide a provide a previous sibling selector, the only solution is using JS. You can use jquery's prev() method for the same.
$(function() {
$(".div2").hover(function() {
$(this).prev().addClass("hoveredBg");
},
function() {
$(this).prev().removeClass("hoveredBg");
});
});
.hoveredBg {
background-color: red;
}
<div class="div1">div 1 hover</div>
<div class="div2">div 2 hover</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This will only help your hover for the previous sibling div only and not burden the browser for next sibling hover, which can be achieved using CSS only.
Try this below code.
$(document).ready(function() {
$(".div2").mouseover(function() {
$(".div1").css("background-color", "red");
});
$(".div2").mouseout(function() {
$(".div1").css("background-color", "");
});
});
/* Works */
.div1:hover+.div2 {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="div1">hover</div>
<div class="div2">hover</div>
Hope this will help you.
Check out this fiddle,
https://jsfiddle.net/rkqhvzyc/
$(document).ready(function() {
$(".div2").hover(function(){
$('.div1').css("background-color", "red");
}, function(){
$('.div1').css("background-color", "white");
});
});
/* Works */
.div1:hover + .div2 {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="div1">hover</div>
<div class="div2">hover</div>
Interesting how nobody pointed out that classes are multiple on a single page,
and no, you should not target .div1 just like that, like many suggested, and expect that all other .div1 in the DOM will not be targeted as-well.
// NONSENSE
$( ".div2" ).hover(
function() {
$(".div1").css( "background-color", "red" );
}, function() {
$(".div1").css( "background-color", "initial" );
}
);
<div class="div1">DIV1</div>
<div class="div2">DIV2 hover me</div>
<div class="div1">DIV1</div>
<div class="div2">DIV2 hover me</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
To reflect the above-mentioned problem - here's a couple of solutions:
// 1. EXAMPLE TARGETING .prev() (NOT FLEXIBLE)
$(".hoverTargetPrev").hover(function() {
$(this).prev(".div1").toggleClass("red");
});
// 2. BETTER EXAMPLE USING .couple PARENT, .closest() AND .find()
$(".div2").hover(function() {
$(this).closest(".couple").find(".div1").toggleClass("red");
});
// 3. EXAMPLE TARGETING .prevAll() and .eq(0) (a bit expensive but...)
$(".hoverTargetNearestPrev").hover(function() {
$(this).prevAll(".div1").eq(0).toggleClass("red");
});
.div2 {color:red;}
.red {background: red;}
<h3> 1. EXAMPLE TARGETING .prev() (NOT FLEXIBLE)</h3>
<div class="div1">DIV1</div>
<div class="div2 hoverTargetPrev">DIV2 hover me</div>
<div class="div1">DIV1</div>
<div class="div2 hoverTargetPrev">DIV2 hover me</div>
<div class="div1">DIV1</div>
<div>Future intruder...</div>
<div class="div2 hoverTargetPrev">DIV2 hover me (will not work any more)</div>
<h3> 2. BETTER EXAMPLE USING .couple PARENT, .closest() AND .find() </h3>
<div class="couple">
<div class="div1">DIV1</div>
<div class="div2">DIV2 hover me</div>
</div>
<div class="couple">
<div class="div1">DIV1</div>
<div class="div2">DIV2 hover me</div>
</div>
<div class="couple">
<div class="div1">DIV1</div>
<div>Future intruder...</div>
<div class="div2">DIV2 hover me (will kork!)</div>
</div>
<h3> 3. EXAMPLE TARGETING .prevAll() and .eq(0) (a bit expensive but...)</h3>
<div class="div1">DIV1</div>
<div class="div2 hoverTargetNearestPrev">DIV2 hover me</div>
<div class="div1">DIV1</div>
<div class="div2 hoverTargetNearestPrev">DIV2 hover me</div>
<div class="div1">DIV1</div>
<div>Future intruder...</div>
<div class="div2 hoverTargetNearestPrev">DIV2 hover me (will work!!)</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Hover on a link and change the background-image of a div - JQuery

I'm having trouble making a div's background-image change when hovering over a link the code looks fine to me so I'm at a loss here is the code:
Javascript:
$('#hover-01').on('mouseover', function(){
$('#hover-change').css('background-image', 'url("images/1.jpg")');
});
$('#hover-01').on('mouseout', function(){, function(){
$('#hover-change').css('background-image', 'url("images/5.jpg")');
});
HTML:
<div class="open-project-link">
<a id="hover-01" class="open-project"
href="project3.html">Bowman Clay</a>
</div>
<div class="responsive-section-image" id="hover-change"
style="background-image: url(images/5.jpg);">
<div class="overlay"></div>
</div>
jQuery version: v2.1.1
Any idea's or advice?
Edit: the code does work however it was a problem with a 3rd party plugin (I assume) so I fixed it with normal javascript and not jQuery
'mousein' isn't an event handler that you can use. You should use mouseover and mouseout, or mouseenter and mouseleave. See jQuery mouse events here.
You also need to give a width/height to your container that will hold the image, since it has no contents. Also, you have two function() declarations in your mouseout function, I fixed it in the following code sample:
$('#hover-01').on('mouseenter', function(){
$('#hover-change').css('background-image', 'url(http://www.w3schools.com/css/trolltunga.jpg)');
});
$('#hover-01').on('mouseleave', function(){
$('#hover-change').css('background-image', 'url(https://www.nasa.gov/sites/default/files/styles/image_card_4x3_ratio/public/thumbnails/image/leisa_christmas_false_color.png?itok=Jxf0IlS4)');
});
#hover-change {
width:1000px;
height:300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="open-project-link">
<a id="hover-01" class="open-project"
href="project3.html">Bowman Clay</a>
</div>
<div class="responsive-section-image" id="hover-change">
<div class="overlay"></div>
</div>
Use this fiddle:
JS:
$('#hover-01').on('mouseenter', function(){
$('#hover-change').css('background-image', 'url("images/1.jpg")');
});
$('#hover-01').on('mouseout', function(){
$('#hover-change').css('background-image', 'url("images/5.jpg")');
});
You can use jQuery's toggleClass() method to solve your problem like this:
$(document).on('ready', function() {
$('#link').on('mouseover', function() {
//alert('sadasd');
$('body').toggleClass('colored');
});
$('#link').on('mouseleave', function() {
//alert('sadasd');
$('body').toggleClass('colored');
});
});
body.colored {
background-color: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<a id="link" href="#">This is a Link</a>
</div>
Hope this helps!
You can use the CSS :hover ~ to change the hover-change div when hover-01 is hovered over as follows:
#divToHover:hover ~ #divToChange {
/*your code here*/
}
#change {
height: 300px;
width: 300px;
background-image: url("//www.google.com/favicon.ico");
}
#hover {
height: 40px;
width: 40px;
background-color: green;
}
#hover:hover ~ #change {
background-image: url(/favicon.ico);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div id="hover">hover</div>
<div id="change"></div>
Try the following code. Make sure to set height and width for the div for which you want the background change.
Issue was with your event name used. Refer here for list of mouse events
$('#hover-01').on('mouseover', function() {
$('#hover-change').css('background-image', 'url("https://placehold.it/350x150/ffff00")');
}).on('mouseout', function() {
$('#hover-change').css('background-image', 'url("https://placehold.it/350x150/ff0000")');
});
.responsive-section-image {
height: 150px;
width: 350px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="open-project-link">
<a id="hover-01" class="open-project" href="project3.html">Bowman Clay</a>
</div>
<div class="responsive-section-image" id="hover-change" style="background-image: url('https://placehold.it/350x150/ff0000')">
<div class="overlay"></div>
</div>

Click and change THIS div

I have 3 divs with the same class (i can't use IDs on them). I find all of them by targeting their class and then - on click - i want to apply some stuff (e.g. change background-color). i only managed to change all of them, but not only the one i'm actually clicking. what am i missing?
var thisDiv = $('.thisDiv');
thisDiv.click(function() {
var i = thisDiv.index(this);
console.log(i);
console.log(thisDiv.css('background-color'));
// this changes all of the div, not only the clicked one
thisDiv.css('background-color', 'red');
// console msg for the code below: Uncaught TypeError: thisDiv[i].css is not a function
// thisDiv[i].css('background-color', 'red');
// i also tried these, which didn't work...
//console.log(thisDiv[i].css('background-color'));
//console.log(thisDiv.eq[i].css('background-color'));
});
.thisDiv{width:50px;height:50px;background-color:lightgrey;float:left;margin:15px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="thisDiv">div 0</div>
<div class="thisDiv">div 1</div>
<div class="thisDiv">div 2</div>
use $(this) will give you the div which you have clicked
$(this).css('background-color', 'red');
use .eq():
thisDiv.eq(i)
as thisDiv is a collection of objects, you can get the specific ones with $(this) or .eq(i).
var thisDiv = $('.thisDiv');
thisDiv.click(function() {
var i = thisDiv.index(this);
thisDiv.eq(i).css('background-color', 'red');
});
.thisDiv {
width: 50px;
height: 50px;
background-color: lightgrey;
float: left;
margin: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="thisDiv">div 0</div>
<div class="thisDiv">div 1</div>
<div class="thisDiv">div 2</div>

How to create javascript function for hovering 3 or 4 element at a time

I want to hover 3 item at a time. when i will put cursor one of them. It should hover other two item.
please can help me anyone. i want to do this with javascript. I have make a model but it is not good. i want to use with function so i can use this again and again. please help me.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<style type="text/css">
.boxes {
float: left;
display: inline;
width:150px;
height:100px
}
.box1 {
width:50px;
padding:10px;
border:1px solid gray;
margin:0px;
height: 20px;
}
.box4 {
display: inline-block;
width:150px;
padding:10px;
border:1px solid gray;
height: 100px;
}
</style>
<script>
$(document).ready(function(){
// box 1
$('.box1').mouseover(function(){
$('.box1').css('background-color', '#F7FE2E');
$('.box4').css('background-color', '#F7FE2E');
$('.hov').css('color', '#0f0');
});
$('.box1').mouseout(function(){
$('.box1').css('background-color', '#FFF');
$('.box4').css('background-color', '#FFF');
$('.hov').css('color', '#fff');
});
$('.box4').mouseover(function(){
$('.box4').css('background-color', '#F7FE2E');
$('.box1').css('background-color', '#F7FE2E');
$('.hov').css('color', '#0f0');
});
$('.box4').mouseout(function(){
$('.box4').css('background-color', '#FFF');
$('.box1').css('background-color', '#FFF');
$('.hov').css('color', '#fff');
});
});
</script>
</head>
<div class="boxes">
<div class="box1">Box 1</div>
</div>
<div class="box4">box4 </div>
<br/>
<div class="boxes">
<div class="box1">Box 1</div>
</div>
<div class="box4">box4 </div>
</body>
</html>
If you group your divs by parent divs, you can use the HTML structure to determine what to highlight. I don't know your exact usage model, but something like this:
<div class="boxgroup">
<div class="box1 hover"></div>
<div class="box2 hover">Link</div>
</div>
<div class="boxgroup">
<div class="box1 hover"></div>
<div class="box2 hover">Link</div>
</div>
And then in your jQuery:
$(document).on('mouseover', '.hover', function () {
var boxgroup = $(this).closest('.boxgroup');
boxgroup.find('.hover').addClass('hovercolor');
boxgroup.find('.hov').css('color', '#0f0');
}).on('mouseout', '.hover', function () {
var boxgroup = $(this).closest('.boxgroup');
boxgroup.find('.hover').removeClass('hovercolor');
boxgroup.find('.hov').css('color', '#000');
});
Here, I use .closest() to find what group the div is in, and then highlight all of the other .hover items in that group.
Example:
http://jsfiddle.net/jtbowden/HZtVP/3/
If you want your divs to not be physically grouped, there are other ways to do what you want.
use a mapping javascript object.
and use class 'like' selector to bind functions to elements which have class starting with ".box"
eg :
$(document).ready(function(){
var mapping = { 'box1':'box4','box4':'box1' };
$("[class^=box]").mouseover(function(){
.........
});

Categories

Resources