Add a class on hover remove class on second hover - javascript

I want to add a class on hover but not remove it when mouse leaves. Instead it must be removed on the second mouse hover. So on mouse hover add class. Mouse leaves class remains. Mouse hovers again class is removed.
This code adds the class but if the mouse leaves the class is removed which is not what I'm trying to achieve.
jQuery('.menuButton').hover(function(){
jQuery('.mainMenuDrop').addClass('show')
}, function() {
jQuery('.mainMenuDrop').removeClass('show')
});

To achieve your requirement of add on first entry and remove on second entry, you can change your existing code:
jQuery('.menuButton').hover(function(){
jQuery('.mainMenuDrop').addClass('show')
}, function() {
jQuery('.mainMenuDrop').removeClass('show')
});
to use .toggleClass
jQuery('.menuButton').hover(function(){
jQuery('.mainMenuDrop').toggleClass('show')
}, function() {
// nothing here
});
As jquery .hover binding is just syntax for mouseenter and mouseleave and you don't need mouseleave, this can be simplified to:
jQuery('.menuButton').on("mouseenter", function() {
jQuery('.mainMenuDrop').toggleClass('show');
});
div { border: 1px solid black; padding: 20px; width: 100px; }
.show { background-color: pink; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='menuButton'>point at me</div>
<div class='mainMenuDrop'>changes here</div>

Related

I need to remove a class after adding it clicking on same checkbox, not the document

I'm clicking on a checkbox to add some animation to a div, but when I want this animation to disappear I can only make it happen through $(document) click. Checkbox must add and then remove the class.
JS
$('#inOrder').click(function(e) {
$('.border').addClass('colorsborder');
e.stopPropagation();
$(document).click(function(e) {
$('.border').removeClass('colorsborder');
});
});
$('#inOrder').click(function(e) {
e.stopPropagation();
});
HTML
<input id="inOrder" type="checkbox" />
You may call toggleClass() method on the jQuery object (element) that you want to add or remove the class from. The method toggleClass will either:
add the desired class when the element doesn't have it.
or remove that class when the element has it already.
Here's a basic, live demo to illustrate the functionality:
const checkbox = $('#inOrder'),
relatedDiv = $('#related');
checkbox.on('change', () => relatedDiv.toggleClass('custom'))
/** just for demo purpose */
#related {
margin: 15px 0;
padding: 10px;
border: 1px solid #ccc;
}
#related.custom {
border-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="inOrder" type="checkbox" />
<div id="related">My appearnace will change on checkbox click</div>
The above demo is pnly meant as a showcase of a possible solution that could be applied to your current problem and it WON'T do the exact thing you want to have unless you apply the required changes you need to suit your actual code/structuring.
Then you want to toggle the class not add it when you click on checkbox
$('#inOrder').click(function(e) {
$('.border').toggleClass('colorsborder');
....

how to display a div1 on hovering div2 and fading div1 on mouseout?

I want to display div1 on hovering div2 and disappear div1 only if mouse is not hovering both div1 and div2.
I tried using the following CSS and jquery. But the div1 disappears immadiately after unhovering div2 and i am unable to access the content of div1.
$(document).ready(function() {
$('.about').hover(
function() {
$('.showsection').slideDown(800).addClass('show');
}
, function() {
$('.showsection').slideToggle(800);
});
});
.showsection{
display:none;
}
.show{
display:block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class=about>
<h1>About</h1>
</div>
<div class="showsection">
<h1>Title</h1>
</div>
This could be done by attaching mouseenter and mouseleave events to the elements you want to show/hide.
These are the requirements:
Show showsection when mouse enters about. This can be done using mouseenter on about
Hide showsection when mouse is not hovering over both showsection and about. This actually means checking two things: the mouse is not hovering showsection when it leaves about and the mouse is not hovering about when it leaves showsection. That means we have to attach mouseleave events to both showsection and about.
The below snippet should help.
// JS
$(document).ready(function() {
// mouse enters .about
$('.about').on('mouseenter', function() {
$('.showsection').slideDown(800);
});
// mouse leaves .about
$('.about').on('mouseleave', function() {
// if mouse is not hovering over .showsection hide it
if (!$('.showsection').is(':hover')) {
$('.showsection').slideToggle(800);
}
});
// mouse leaves .showsection
$('.showsection').on('mouseleave', function() {
// if mouse is not hovering over .about hide .showsection
if (!$('.about').is(':hover')) {
$('.showsection').slideToggle(800);
}
});
});
/* CSS */
.showsection {
display: none;
background: #ddd;
}
h1 { margin: 0; }
.about { background: #eee; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class=about>
<h1>About</h1>
</div>
<div class="showsection">
<h1>Title</h1>
</div>
The CSS :hover attribute will only control the element which it is assigned to, in your case presumable div1. So, you are going to have to use JavaScript.
With JavaScript attach a mouseenter and mouseleave event to div1. Inside those event listener functions, control what you want div2 to do.
That's basically how to do it.

Mouseout and click

When a user mouses over a div it should change to the color red, when they mouse out it should change back to transparent. When they click on the div, it should change to color red.
For some reason, the mouse out event listener is conflicting with the click event listener. Can someone help? When I click on the div, it doesn't change to red.
div$.on('mouseover', function () {
$(this).css('background-color', 'red');
});
div$.on('mouseout', function () {
$(this).css('background-color', 'white');
});
div$.on('click', function () {
$(this).css('background-color', 'red');
});
Note, I have to apply a background image dynamically to each element, so using CSS classes to add the background image is out of the question (because I don't know it before hand).
You could set a boolean variable to confirm that the click has occurred and then only run the mouseout code if the variable is false like this:
var is_clicked = false;
div$.on('mouseover', function () {
$(this).css('background-color', 'red');
});
div$.on('mouseout', function () {
if(!is_clicked) {
$(this).css('background-color', 'white');
}
});
div$.on('click', function () {
$(this).css('background-color', 'red');
is_clicked = true;
});
Note: For multiple div elements user multiple is_clicked variables
You can always do a CSS implementation with :hover; just make sure to add a specifying class to each element you would like this effect on.
1. :hover and jQuery
var div$ = $('.redHover'); // name the class whatever you like
div$.on('click', function () {
$(this).css('background-color', 'red');
});
div {
display: inline-block;
}
.redHover {
height: 100px;
width: 100px;
border: 1px solid black;
}
.redHover:hover {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='redHover'></div>
<div class='redHover'></div>
<div class='redHover'></div>
2. :hover and vanilla JS
var els = document.querySelectorAll('.redHover');
for (var i = 0; i < els.length; ++i) {
els[i].addEventListener('click', function() {
this.style.backgroundColor = 'red';
});
}
div {
display: inline-block;
}
.redHover {
height: 100px;
width: 100px;
border: 1px solid black;
}
.redHover:hover {
background: red;
}
<div class='redHover'></div>
<div class='redHover'></div>
<div class='redHover'></div>
Instead use mouseenter insead of mouseover see why.
The best thing you can go with would be the following notes:
To those elements with hover effect add a class like hoverable.
Hover effect is only applied to those elements having this class.
HTML:
<div class="hoverable"></div>
CSS:
.hoverable:hover{
background-color: red
}
JavaScript:
div$.on('click', function () {
$(this).css('background-color', 'red');
});
In this way, you can simply decide whether an element should be hover-able or not by adding or removing hoverable class. Also hover effect is applied in CSS level not JavaScript, which is more acceptable.
As far as I understand you really want to change picture in the div, not just background color which is relatively easy. Try this:
<div class="hoverable">
<img src="myImg.jpg" />
</div>
//css
.hoverable img{visibility:hidden;}
.hoverable:hover img{visibility:visible;}
.clicked img{visibility:visible!important;}
//JS
$('.hoverable').click(function(){
$(this).addClass('clicked');
});

Removing and adding class on hover

I am making a panel of photos/text. All the panels will have an overlay color on them except the first one which has an active class on page load which removes the overlay. As you hover over the second/third etc panels, the overlay active class will remove from first panel and go onto the one that is hovered.
Right now it is only active on page load, I can't seem to get the class off the first div and onto the second div on hover.
if ( $(".overlay:first") ){
$(".overlay:first").addClass("active");
}
else {
if ( $(".overlay:not(:first)").hover ){
$(".overlay:first").removeClass("active");
}
}
https://jsfiddle.net/egdkuh16/3/
There is no need to use JavaScript or jQuery for this. It's best used in CSS with the :hover pseudo-selector. It's also much easier today.
.overlay:first-child {
background: white;
}
.overlay:first-child:hover {
background: gold;
}
If you insist on using jQuery, you can try this
$(".overlay:first").on("mouseover", function() {
$(this).addClass("active");
}).on("mouseout", function() {
$(this).removeClass("active");
});
.active {
background: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="overlay">First overlay class</div>
<div class="overlay">Second overlay class</div>
This approach is highly frowned upon though
In jQuery, you could do it like this:
$(document).ready(function() {
// Make the first active
$(".overlay:first").addClass("active");
// On hover remove all active classes from .overlay
// and add .active only to the one that is hovered
$(".overlay").hover(function() {
$(".overlay").removeClass("active");
$(this).addClass("active");
});
});
but Richard Hamilton's answer is much better and cleaner.
You can use jQuery's on. For example:
$(".overlay:first").addClass("active");
$(".overlay").on("hover", function(){
$(this).addClass("active");
$(".overlay:first").removeClass("active")
});

New class keeps old class behaviour

I'm taking by first babysteps in jQuery and stumbled upon a problem I can't seem to get around.
I couldn't find an article that quite described what my problem was, so I would like to try to get an answer this way.
I don't understand why my objects keep behaving like their former class.
When I setup a hover action for a class, and change the class of the object by clicking, jQuery keeps doing the animation for the new class.
I used toggleClass() and removeClass/ addClasswithout any result:
https://jsfiddle.net/biest9160/f0na6sro/
var wide = function() {
$(this).animate({ 'width': '120px' }, 200);
}
var normal = function() {
$(this).animate({ 'width': '100px' }, 200);
}
$(document).ready(function() {
$('.class1').hover(wide, normal);
$('.class1').click(function() {
$(this).toggleClass('class1 class2');
})
})
div {
width: 100px;
height: 100px;
border: 1px solid #000;
margin: auto;
}
.class2 {
background: #555;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box1" class="class1">box1</div>
<div id="box1" class="class1">box2</div>
<div id="box1" class="class1">box3</div>
<div id="box1" class="class1">box4</div>
I don't understand why the the hover action is triggered while the object has a new class.
Initialy you attach the event to the element with the class name. After the class is changed the event remains on the element.
To remove the event you can use .unbind. To remove .hover event you can check this answer.
A working example using .unbind to remove the event and after to reattach it will look like in the snippet (basically is toggle hover event):
var wide = function(){
$(this).animate({'width':'120px'},200);
}
var normal = function(){
$(this).animate({'width' : '100px'},200);
}
$(document).ready(function(){
$('.class1').hover(wide,normal);
$('.class1').click(function(event){
var $this = $(this);
$this.unbind('mouseenter mouseleave'); // remove hover
if( $this.hasClass('class2'))
{
$this.hover(wide, normal); // reattach hover
}
$this.toggleClass('class1 class2');
})
})
div{
width:100px;
height:100px;
border: 1px solid #000;
margin: auto;
}
.class2{
background: #555;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box1" class="class1">box1</div>
<div id="box1" class="class1">box2</div>
<div id="box1" class="class1">box3</div>
<div id="box1" class="class1">box4</div>
Use .on() menthod to bind the event which will actually bind the event on the parent of the class.
Here is the example:
$(document).on("click", '.class1', function(){
$(this).toggleClass('class1 class2');
});
This will defiantly work...

Categories