How do I change color with onmouseover? - javascript

I wonder how I can do those 2 functions into 1 function instead.
function test1() {
document.getElementById('div1').style.color = 'red';
}
function test2() {
document.getElementById('div1').style.color = 'blue';
}
<div onmouseover="test1()" onmouseout ="test2()" id="div1">
</div>

pass the object and color to the test method
function test(thisObj, color)
{
thisObj.style.color = color;
}
<div onmouseover="test(this, 'red')" onmouseout ="test(this, 'green')" id="div1"></div>

you can achieve this with just css
https://jsfiddle.net/dango_x_daikazoku/404o04co/1/
#test1{
color:red;
cursor:default;
}
#test1:hover{
color:blue;
}

If you want to do with JavaScript you can do in this way.
JS :
window.onload = function(){
var htmlDiv = document.getElementById("div1");
htmlDiv.addEventListener('mouseover',function(){
htmlDiv.style.color = "red";
})
htmlDiv.addEventListener('mouseout',function(){
htmlDiv.style.color = "blue";
})
}
HTML :
<style>
#div1{
width:100px;
height : 100ppx;
border :1px solid black;
}
#div1 {
color:blue;
}
</style>
Here is the plunker

I would recommend CSS :hover Selector
If you want to change class from javascript, i would recommend jQuery:
jQuery addClass() Method,
jQuery removeClass() Method,
hover()
mouseover()
hasClass()
As for your request to do this with one function, you could write:
function manageHoverColor(){
if( $("#hoverTestDiv").hasClass("mouseHovered") ){
$( "#hoverTestDiv" ).removeClass('mouseHovered');
}else{
$( "#hoverTestDiv" ).addClass('mouseHovered');
}
}
$( "#hoverTestDiv" ).mouseover(manageHoverColor);
$( "#hoverTestDiv" ).mouseout(manageHoverColor);
or you could do:
$( "#hoverTestDiv" ).mouseover(function() {
$( "#hoverTestDiv" ).addClass('mouseHovered');
});
$( "#hoverTestDiv" ).mouseout(function() {
$( "#hoverTestDiv" ).removeClass('mouseHovered');
});
.ordinaryText {
color: #00FF00;
}
.ordinaryText.mouseHovered {
color: #FF0000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="hoverTestDiv" class="ordinaryText" > I am div to test jQuery mouse hover <div>

Related

JQuery hide() and show() functions overlaping each other

I'm trying to show and hide elements on my page based on clicks on an image code goes as follows.
jQuery(function($) {
jQuery(".elementor-widget-image").click(function() {
var contentPanelId = jQuery(this).attr("id");
switch (contentPanelId) {
case "capacitacion":
console.log(contentPanelId+' has been clicked');
$( "#capacitacion-content" ).show( "slow");
break;
case "practicas":
console.log(contentPanelId+' has been clicked');
$( "#capacitacion-content" ).hide( "slow");
$( "#bpm-content" ).show( "slow");
break;
}
});
});
The problem is when i press the first image comes and goes normally but the second image don't show at all, is it a logic problem? cause i clearly telling the system th hide one and show the other.
replce
$( "#capacitacion-content" ).hide( "slow");
$( "#bpm-content" ).show( "slow");
by
$("#capacitacionContent" ).hide();
$("#bpmContent" ).show();
and try
jQuery(function($) {
$("#capacitacion-content").hide();
$("#bpm-content").hide();
jQuery(".elementor-widget-image").click(function() {
var contentPanelId = jQuery(this).attr("id");
switch (contentPanelId) {
case "capacitacion":
console.log(contentPanelId + ' has been clicked');
$("#bpm-content").hide("slow");
$("#capacitacion-content").show("slow");
break;
case "practicas":
console.log(contentPanelId + ' has been clicked');
$("#capacitacion-content").hide("slow");
$("#bpm-content").show("slow");
break;
}
});
});
.elementor-widget-image {
cursor: pointer;
}
#capacitacion-content {
background: red;
height: 100px;
width: 100px;
}
#bpm-content {
background: green;
height: 100px;
width: 100px;
}
#practicas {
margin-top: 10px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="elementor-widget-image" id="capacitacion">Click to test capacitacion </div>
<div class="elementor-widget-image" id="practicas">Click to test practicas</div>
<div id="capacitacion-content"> </div>
<div id="bpm-content"></div>

How to toggle an animation in Jquery

I am trying to make an animation on a navigation menu where when an option is clicked the other two fade out, since .fadeToggle had problems with positioning for me I decided to just animate the opacity to 0, and then back to 1 when clicked on again. (I left the CSS out the the code posted down below)
https://jsfiddle.net/L703yvke/
<div id='bckDrp'>
<div id='nav'>
<ul id='navLst'>
<li class='navOp' id='hme'>Home</li>
<li class='navOp' id='abt'>About</li>
<li class='navOp' id='prt'>Portfolio</li>
</ul>
</div>
</div>
var main = function(){
$('#hme').click(function(){
$('#abt, #prt').animate({opacity: 0},300 );
});
if($('#abt, #prt').css('opacity') == 0) {
$('#hme').click(function(){
$('#abt, #prt').animate({opacity: 1},300 );
}
)};
}
$(document).ready(main);
The main function only runs once. So you are only doing that if-statement once. Also you are binding click events, which I don't think is what you are expecting it to do. Instead you can simply use a if-else and have your condition inside the click event:
var main = function(){
$('#hme').click(function(){
if($('#abt, #prt').css('opacity') == 0)
$('#abt, #prt').animate({opacity: 1},300 );
else
$('#abt, #prt').animate({opacity: 0},300 );
});
}
Demo
I would heavily recommend handling the animation as a transition in CSS and simply toggling a class.
CSS
#abt, #prt{
opacity:1;
transition: opacity 300s;
}
#abt.hide, #prt.hide{
opacity:0;
}
jQuery
$('#hme').on('click', function(){
$('#abt, #prt').toggleClass('hide');
});
Change your code :
var main = function() {
$('#hme').click(function(){
var op = $('#abt, #prt').css('opacity');
if (op == 1)
$('#abt, #prt').animate({opacity: 0},{duration:300} );
else if(op == 0)
$('#abt, #prt').animate({opacity: 1},{duration:300} );
})
}
$(document).ready(function(){
main();
})
Final code :
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id='bckDrp'>
<div id='nav'>
<ul id='navLst'>
<li class='navOp' id='hme'>Home</li>
<li class='navOp' id='abt'>About</li>
<li class='navOp' id='prt'>Portfolio</li>
</ul>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
var main = function() {
$('#hme').click(function(){
var op = $('#abt, #prt').css('opacity');
if (op == 1)
$('#abt, #prt').animate({opacity: 0},{duration:300} );
else if(op == 0)
$('#abt, #prt').animate({opacity: 1},{duration:300} );
})
}
$(document).ready(function(){
main();
})
</script>
</body>
</html>
First, you had a typo.... )}; the brackets are reversed. They should be });
Then you could simplify a great deal by just using the built in toggleClass(); function and dynamically getting the clicked element rather than needed to refer to each and every id used. This means you can add/subtract from the #nav list and the function will work regardless of the element ids. The "fade" is all handled in the CSS and you don't need to edit the function at all.
the only thing you'd need to edit from here are nav items in the HTML. (if they change...)
var main = function(){
$('#nav li').on('click', function() {
var thisNav = $(this);
thisNav.toggleClass('active');
$('#nav li').not(thisNav).toggleClass('fadeit');
});
}
$(document).ready(main);
ul { list-style: none; margin: 10px; padding:0; }
li {
display: block;
padding: 5px 10px;
margin: 10px 0;
text-align: center;
text-transform: uppercase;
background: #eee;
border: 1px solid #ddd;
/* below handles the opacity fade */
opacity: 1;
transition: all 1s; }
.active, li:hover { background: #fee; }
/* below handles the opacity fade */
.fadeit { opacity: 0; transition: all 1s; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='bckDrp'>
<div id='nav'>
<ul id='navLst'>
<li class='navOp' id='hme'>Home</li>
<li class='navOp' id='abt'>About</li>
<li class='navOp' id='prt'>Portfolio</li>
</ul>
</div>
</div>
You need set your code with the sentence if, inside the callback .click;
This is necessary because the JS code is loaded only once and in this moment your sentence (if) is read only with the event .loaded()
This is a solution for you:
var main = function(){
$('#hme').click(function(){
$('#abt, #prt').animate({opacity: 0},300 );
if($('#abt, #prt').css('opacity') == 0) {
$('#abt, #prt').animate({opacity: 1},300 );
}else{
$('#abt, #prt').animate({opacity: 0},300 );
};
});
}
$(document).ready(main);

event handler in javascript

I have this snippet, What I want to do is when you onclick the div it will not be affected by the mouseover and mouseout.. thank you very much for all your help..
<div id="div" onmouseover="over_div()" onmouseout="out_div()" onclick="click_div()" style="width:100px; height:100px; border:2px solid black"></div>
<script>
function click_div(){
document.getElementById("div").style.backgroundColor="red";
}
function over_div(){
document.getElementById("div").style.backgroundColor="green";
}
function out_div(){
document.getElementById("div").style.backgroundColor="white";
}
</script>
You could do something like this:
<div id="div" onmouseover="over_div()" onmouseout="out_div()" onclick="click_div()" style="width:100px; height:100px; border:2px solid black"></div>
<script type="text/javascript">
var isClicked = false;
function click_div(){
isClicked = true;
document.getElementById("div").style.backgroundColor="red";
}
function over_div(){
if(!isClicked )
document.getElementById("div").style.backgroundColor="green";
}
function out_div(){
if(!isClicked )
document.getElementById("div").style.backgroundColor="white";
isClicked = false;
}
</script>
However, using global variable is a bad practice. If you understand the concept of closure, you can use something like this instead :
<div id="div" style="width:100px; height:100px; border:2px solid black"></div>
<script type="text/javascript">
(function()
{
var div = document.getElementById("div");
var isClicked = false;
div.addEventListener("click", function() {
div.style.backgroundColor = "red";
isClicked = true;
});
div.addEventListener("mouseover", function() {
if(!isClicked)
div.style.backgroundColor = "green";
});
div .addEventListener("mouseout", function() {
if(!isClicked)
div.style.backgroundColor = "white";
isClicked = false;
});
}
)();
</script>
Using this, the div and isClicked variables won't be in conflicted with other variable that could have the same name later in your code.
You can't achieve this with events added to the tag of the element. Here is a jsfiddle which works as you want:
http://jsfiddle.net/krasimir/Ru5E5/
Javascript:
var element = document.getElementById("div");
var isClicked = false;
element.addEventListener("click", function() {
isClicked = true;
element.style.backgroundColor="red";
});
element.addEventListener("mouseover", function() {
if(isClicked) return;
element.style.backgroundColor="green";
});
element.addEventListener("mouseout", function() {
if(isClicked) return;
element.style.backgroundColor="white";
});
HTML
<div id="div" style="width:100px; height:100px; border:2px solid black"></div>
Set a global flag up and when you do your on click event set it to 1. In your mouse out event test to see if flag is 1. If it is then don't change the background colour.
If you want the onMouseOver and onMouseOut events to be completely disabled, you can also remove the event handlers from them by adding only two lines of code.
<div id="div" onmouseover="over_div()" onmouseout="out_div()" onclick="click_div()" style="width:100px; height:100px; border:2px solid black"></div>
<script>
function click_div(){
document.getElementById("div").style.backgroundColor="red";
// Disable the other two events
document.getElementById("div").onmouseover=null;
document.getElementById("div").onmouseout=null;
}
function over_div(){
document.getElementById("div").style.backgroundColor="green";
}
function out_div(){
document.getElementById("div").style.backgroundColor="white";
}
</script>

jQuery animation without queuing

I am trying to figure out how .stop() and clearQueue() work.
Here is my sample code in jsfiddle: http://jsfiddle.net/PsTQv/1/
You will see the animation is queuing if hove over several blocks.
To work around with this, I tried to use stop() and clearQueue.Simple add stop after hide() or show() or both won't work.The behaviors like:
1. .stop().hide() : text disappears at last;
2. .stop.show(): text is alway there, won't be hidden any more
3. add both: Same as only add to show()
4. add .clearQueue().stop() in the beginning: text disappears at last, like .stop().hide()
I want to understand what the differences between clearQueue and stop to explain the behaviors above.Also I want to figure out how to achieve the animation without queueing in this example, that is, hover over the block and the text shows up in the slide effect.
Thanks
You need to clear the animation queue in the callback function that executes when the slide animation is done:
$('.block').hover(function(){
$('section').hide('fast');
//$('section').stop().show('slide',{direction:'left'},1000);
$('section').show('slide',{direction:'left'},1000,function(){$(this).clearQueue()});
},function(){});
jsFiddle
var inAnimation = new Array();
$("div").hover(function(){
if (!inAnimation[$("div").index(this)] ) {
$(this).animate({ width: "200px" });
}
}, function() {
inAnimation[$("div").index(this)] = true;
$(this).animate({ width: "100px" }, "normal", "linear", function() {
inAnimation[$("div").index(this)] = false;
})
});
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>clearQueue demo</title>
<style>
div {
margin: 3px;
width: 40px;
height: 40px;
position: absolute;
left: 0px;
top: 30px;
background: green;
display: none;
}
div.newcolor {
background: blue;
}
</style>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<button id="start">Start</button>
<button id="stop">Stop</button>
<div></div>
<script>
$( "#start" ).click(function() {
var myDiv = $( "div" );
myDiv.show( "slow" );
myDiv.animate({
left:"+=200"
}, 5000 );
myDiv.queue(function() {
var that = $( this );
that.addClass( "newcolor" );
that.dequeue();
});
myDiv.animate({
left:"-=200"
}, 1500 );
myDiv.queue(function() {
var that = $( this );
that.removeClass( "newcolor" );
that.dequeue();
});
myDiv.slideUp();
});
$( "#stop" ).click(function() {
var myDiv = $( "div" );
myDiv.clearQueue();
myDiv.stop();
});
</script>
</body>
</html>

Change div text with jQuery Toggle

When using slideToggle, how to change the Text close/show?
I did a simple one, but cannot get the text change back.
Here is what I did:
$(document).ready(function(){
$('.open').click(function(){
$('.showpanel').slideToggle('slow');
$(this).text('close');
});
$('.open2').click(function(){
$('.showpanel2').slideToggle('slow');
$(this).text('close');
});
});
body{
font-size:20px;
}
#box{
border:2px solid #000;
width:500px;
min-height:300px;
}
.open,.open2 {
width:450px;
height:50px;
background:blue;
margin:5px auto 0 auto;
color:#fff;
}
.showpanel,.showpanel2{
width:450px;
height:300px;
margin:0 auto 10px auto;
background:red;
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box">
<div class="open">Show</div>
<div class="showpanel">This is content</div>
<div class="open2">Show</div>
<div class="showpanel2">This is content</div>
</div>
http://jsfiddle.net/9EFNK/
You can use the is() assertion method to check whether the panel is open or closed in the animation's callback and set the text accordingly - http://jsfiddle.net/9EFNK/7/
$('.open').click(function(){
var link = $(this);
$('.showpanel').slideToggle('slow', function() {
if ($(this).is(':visible')) {
link.text('close');
} else {
link.text('open');
}
});
});
Just add a simple if statement to test the text like so
$('.open').click(function(){
$('.showpanel').slideToggle('slow');
if($(this).text() == 'close'){
$(this).text('Show');
} else {
$(this).text('close');
}
});
Like this DEMO
Not the prettiest of methods, but it does the job in a single statement.
$(this).text(($(this).text() == 'Close') ? 'Show' : 'Close');
Use .toggle()
Here is Working Demo
$('.open').click(function(){
$('.showpanel').slideToggle('slow');
}).toggle(function() {
$(this).text('Hide');
}, function() {
$(this).text('Show');
});
check this may be user question is solve Fiddle
Here's an updated version http://jsfiddle.net/9EFNK/1/
You can simply toggle a class on close/open, perform a check for that class and change the contained text accordingly
if( $(this).hasClass('active') )
$(this).text('open');
else
$(this).text('Show');
$(this).toggleClass('active');
try this demo
$(document).ready(function(){
$('.open').toggle(function(){
$('.showpanel').slideToggle('slow');
$(this).text('close');
}, function(){
$('.showpanel').slideToggle('slow');
$(this).text('Show');
});
$('.open2').toggle(function(){
$('.showpanel2').slideToggle('slow');
$(this).text('close');
}, function(){
$('.showpanel2').slideToggle('slow');
$(this).text('Show');
});
});​
Use this
jQuery.fn.toggleText = function() {
var altText = this.data("alt-text");
if (altText) {
this.data("alt-text", this.html());
this.html(altText);
}
};
Here is how you use it
jQuery.fn.toggleText = function() {
var altText = this.data("alt-text");
if (altText) {
this.data("alt-text", this.html());
this.html(altText);
}
};
$('[data-toggle="offcanvas"]').click(function () {
$(this).toggleText();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button data-toggle="offcanvas" data-alt-text="Close">Open</button>
You can even use html provided it's html encoded properly

Categories