How to reverse hover state with jQuery? - javascript

My assignment requires that I use jquery only. Doesn't seem practical but I'm limited. I was able to figure out how to do a hover state but when the styles get applied, it stays. So check this out..
$(".cta-button").css({
background: "#476887",
"text-align": "center",
width: "173px",
height: "40px",
margin: "62px auto 33px",
cursor: "pointer"
});
$(".cta-button").hover(function() {
$(this).css("background-color", "#509de5");
});
Of course when I'm no longer hovering, I want it to revert back to it's original background color. How do I go about doing this? Thanks!!

You can easily achieve that by using the hover method of jQuery
As stated in the docs, this method can accept one to two arguments, the first one is called the handlerIn which can be translated as the hover state, mouse enter, etc and the handlerOut which corressponds to the 'mouse leave'
So to achieve what you want you can try something like this
$('DOM_NODE').hover(mouseEnter, mouseLeave);
function mouseEnter() {
// do something when the mouse enters the dom node
};
function mouseLeave() {
// do something when the mouse leaves the dom node
};

You can add mouseover eventa fiddle
$(".cta-button").css({
background: "#476887",
"text-align": "center",
width: "173px",
height: "40px",
margin: "62px auto 33px",
cursor: "pointer"
});
$(".cta-button").hover(function() {
$(this).css("background-color", "#509de5");
}).mouseover(function() {
$(this).css("background-color", "#476887");
});

Related

Remove div element on click jQuery not working

What I need :
I am trying to create tags on the click of a button. I was successful with my attempt to create divs on the click.
Problems :
As in all the websites one has seen, like in stack-overflow or when you write email addresses , as you finish writing the text a "tag" is formed with a "remove" button when you hover.
Now I want something like this, but I am confused in how to show that cross on the divs.
Also my problem is when I use elements, I am also giving some background color but that is static. And if the text grows then there is no background color on the part of the text.
How should I go about this problem ?
This is what I have tried so far : http://jsfiddle.net/abhighosh18/wk9uxfz5/1/
JS :
$('.btnAdd').on('click', function () {
$('<div/>', {
id: 'newCo',
title: $("#prodName").val(),
text: $("#prodName").val()
}).css({
fontWeight: 700,
width : '30px',
background : 'lightblue',
padding: '2px',
margin: '5px',
float : 'left'
}).appendTo("#content");
});
$('#newCo').on('click',function(){
$(this).remove();
});
Some illumination --
$('#newCo').on('click',function(){
$(this).remove();
});
The above won't work because the #newCo element does not exist at the time that line executes.
$(document).on('click','#newCo',function(){ $(this).remove(); });
This refactored line of code listens to the document and WILL work on elements that don't exist at the time the DOM is first loaded. However, ID is not what you want to use here... because IDs need to be unique and there would quickly be several div withs the same ID if you click the .btnAdd element.
There are many ways to accomplish what you want, I just wanted to illustrate why your approach is failing.
THE FIX: you could chain .addClass("removable-tag") within your div-creating click function (before .appendTo()), and listen to $(document).on('click','.removable-tag',function(){...});, and THAT would function as intended.
You can use display: inline-block css property and min-width instead of width:
$('.btnAdd').on('click', function () {
$('<div/>', {
id: 'newCo',
title: $("#prodName").val(),
text: $("#prodName").val()
}).css({
fontWeight: 700,
minWidth : '30px',
background : 'lightblue',
padding: '2px',
margin: '5px',
display: 'inline-block'
}).appendTo("#content");
});
http://jsfiddle.net/Lathtqd8/
NOTE: What follow is an answer to this part of question ( before update ) :
Now what I need is the CSS for the divs to be placed side-by-side. I
have seen the code for doing so, but I need to know how to write the
code for dynamically generated divs.
Another thing i tried was creating buttons instead of divs. That
placed my buttons side by side without any extra effort from CSS.
add this to your css :
#newCo {
float: left;
}
and remove the forcing width : '30px', from your JS code otherwise it will get broken on large content.
http://jsfiddle.net/tunecino/wk9uxfz5/5/
Add some class not id when you want to add multiple elements.
snippet added
--joy
//javascript
$('.btnAdd').on('click', function () {
$('<div/>', {
class: 'newCo',
title: $("#prodName").val(),
text: $("#prodName").val(),
'data-idn':'some_unique_number'
}).append('<a>x</a>')
.appendTo("#content")
.find('a').click(function(){
var idn = $(this).parent().data('idn');
$(this).parent().remove();
//removeCallback(idn); //call anything with idn if required
});
});
/*CSS*/
.newCo{float:left;min-width:30px;background:lightblue;font-weight:700;padding:2px;margin:5px;}
.newCo > a {cursor:pointer;margin:0 0 0 3px;border-radius:50%;color:red;padding:0;text-shadow:0px 0px 1px #fff;font-weight:200;font-size:16px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Product Name:<input id="prodName" type="text">
<button class="btnAdd" value="Click Me!">Add Product</button>
<br/><br/><br/><div id="content" height="100px" width="100px" style="color:blue"></div>
try this:
$("#mydiv").off('click');

jQuery slide animation on existing divs after prependTo

I have this semi-slider-style UI where new terms are added in from the left: http://jsfiddle.net/v4v5cvkz/. I'm using the jQuery prependTo function to do this. My issue is that I want the terms that are already displayed to perform an animated slide to the right when a new term gets added, rather than suddenly "appear" in the correct position. I did try adding a "displayed" class to terms that had successfully shown up, and tried adding a slide-to-right animation after that, but that didn't quite achieve the effect I was going for (the "displayed" objects were moved much further to the right than I expected).
Here is the problematic code (you'll probably want to view the fiddle to see it in context though):
function addToStream(term, delay) {
setTimeout(function(){
$("<div />")
.addClass("stream_term")
.html(term)
.css({
opacity: 0
})
.prependTo("#stream_terms")
.animate({opacity:1},
{ duration: 1000,
complete: function() {
$(this).addClass("displayed");
}
});
}, delay);
}
Any help here would be greatly appreciated. Thank-you!
*Note: I have access to jQuery UI in my code, though it isn't linked in the fiddle. Also, if anyone knows of a plugin that can do this sort of thing better than I can, please let me know. The closest one I was able to find was Fraction Slider, but I didn't find it obvious how to create a similar UI with it (it might also be overkill for my purposes).
Here's a way to do it:
function addToStream(term, delay) {
setTimeout(function(){
var newDiv = $("<div />");
newDiv.addClass("stream_term")
.html(term)
.css({
opacity: 0,
display: 'none'
}).prependTo("#stream_terms");
var width = newDiv.width();
var height = newDiv.height();
newDiv.css({
width: 0,
height: height,
display: 'inline-block'
})
.animate({
width: width,
margin: '0 10px',
padding: '5px 10px'
}, 1000)
.animate({opacity: 1}, 1000, function(){
$(this).addClass("displayed");
});
}, delay);
}
It also needs the following CSS changes:
.stream_term {
padding: 0;
margin: 0;
overflow: hidden;
}
DEMO: http://jsfiddle.net/StathisG/hqg29p6r/1/

Color cycling some elements' css properties with jQuery, :hover gets stuck and erratic

I'm color cycling through the color, background-color and border-color css properties of some elements with the help of jQuery and this little plugin.
I'm doing this:
var currentColor = myRandNumber; // I get this variable from the main page
var myWebColors = [ '#49aea2', '#5da270', '#a1b144', '#ceb33d', '#ce812d',
'#c44e4e', '#ac4275', '#705f91', '#4d6791', '#5199a4' ];
window.setInterval( animateColor, 2000 ); // not using requestAnimationFrame
// for browser compatibility
function animateColor() {
$(".new-project-header, .button a:active,
#logo, ul#menu-main-nav li a:active, ul#menu-main-nav li.contact a,
ul#menu-main-nav li.contact a:visited, .footer-twitter,
.footer-mail").animate(
{
backgroundColor: myWebColors[currentColor]
}, "slow");
$("a:hover, p a:hover, ul#menu-main-nav li.contact a:hover,
h3.portfolio-item-title a:hover").animate(
{
color: myWebColors[currentColor]
}, "slow");
$("p a, p a:visited").animate(
{
borderColor: myWebColors[currentColor]
}, "slow");
if (currentColor == 9) { // the following cycles through the array
// in an endless loop
currentColor = 0;
} else {
currentColor++;
}
}
EDIT: jsfiddle HERE!
The problem I'm having is that when I hover over p a, while jQuery does the color cycling just fine, but once I mouseout the link will stay at its :hover state, with the latest color it cycled into.
It's even worse when I hover over ul#menu-main-nav li. It'll change the a:hover color, when that should only be applied to ul#menu-main-nav li.contact. It's like this latter selector :hover state is taking precedence over the css of the former.
Maybe I should do everything manually with on events? Maybe I should 'reset' all non- :hover states at the end of each loop step? Maybe all of this is overkill and I should try a different approach?
Thanks!
You need to change the state back to default when the mouse exits the element. I.e. hover completes.
JQuery hover can do this easily.
$( "a" ).hover(
function() {
$( this ).animate({ color: myWebColors[currentColor] }, "slow");
}, function() {
$( this ).animate({ color: default_color }, "slow");
}
);
Just out of curiosity, why wouldn't you use CSS:hover property as explained here http://www.w3schools.com/cssref/sel_hover.asp ?
First, you have a loop (setInterval()) that is running even if you didn't hover anything. It is useless.
So, i make an update of your Fiddle with setTimeout(). You can start from something like this. I also replaced :hover statments by event handlers. I don't know if it is ok for you. But this is how I should have done it. Hope it'll help.

Possible to toggle/animate between two sizes using jQuery?

Basically I have a small div that is initially styled to 60x60. I have created click event that animates the expansion of the div:
$("#myDiv").click(function () {
$(this).animate(
{
width: "350px",
height: "300px"
}, 500);
}
I would like to reverse this animation if someone clicks the div again. Is there anyway to toggle between the original size and the expanded size (still using the animate function) with each click?
I found the toggleClass function but I don't think this will work with animiate.
You can see a basic fiddle here: http://jsfiddle.net/NS9Qp/
$("#myDiv").toggle(function() {
$(this).stop().animate({
width: "350px",
height: "300px"
}, 500);
}, function() {
$(this).stop().animate({
width: "60px",
height: "60px"
}, 500);
});
Example.
The jQuery toggle() function allows you to define two or more functions to cycle through on each mouse click. In this case, the first one (triggered on the first click) expands the div and the second one (triggered on the second click) resets it. On the third click, it starts back at the first one, and so on.
More about toggle() here.
just to be different :
var size=[];
$("#cornerBox").click(function(){
$(this).width() >= 350 ? size=[60, 60] : size=[350, 300];
$(this).stop().animate({ width: size[0], height: size[1] },500);
});
Fiddle: http://jsfiddle.net/NS9Qp/1/
I ended up using jQuery UI's animated toggleClass effect: http://jqueryui.com/demos/toggleClass/
super simple code:
$('h2').click(function() {
$(this).next().toggleClass("hidden", 1000);
});
Do not hardcode css styles (in my example I used inline css for myDiv element, put this in css files).
<div id="myDiv" style="background:red; width: 60px; height: 60px;"></div>
<script type="text/javascript">
var div = $('#myDiv');
div
.attr('defWidth', div.width())
.attr('defHeight', div.height())
.toggle(function() {
$(this).stop().animate({width: "350px", height: "300px"}, 500);
}, function() {
$(this).stop().animate({width: $(this).attr('defWidth'), height: $(this).attr('defHeight')}, 500);
}
);
</script>
What I do for cases like this, is store a transformation array.
var transforms = { 'height0': 60, 'width0': 60, 'height1': 300, 'width1': 350};
Then, store a toggle between 0 or 1, and use the corresponding values for the animation.
EDIT: combine this with the previous example of toggle, and you've got yourself a solid working solution!

jQuery slideUp to show the element and not hide

jQuery's slideUp effect hides the element by sliding it up, while slideDown shows the element. I want to show my div using slideUp. can anyone guide me ? thanks
$("div").click(function () {
$(this).hide("slide", { direction: "down" }, 1000);
});
http://docs.jquery.com/UI/Effects/Slide
It's a little more complex than just saying slideUpShow() or something, but you can still do it. This is a pretty simple example, so you might find some edge-cases that need adressing.
$("#show-animate-up").on("click", function () {
var div = $("div:not(:visible)");
var height = div.css({
display: "block"
}).height();
div.css({
overflow: "hidden",
marginTop: height,
height: 0
}).animate({
marginTop: 0,
height: height
}, 500, function () {
$(this).css({
display: "",
overflow: "",
height: "",
marginTop: ""
});
});
});
Here's a fiddle showing the slideUp/slideDown methods, the same effects using animate, and a modified version using animate that goes in reverse: http://jsfiddle.net/sd7zsyhe/1/
Since animate is a built-in jQuery function, you don't need to include jQuery UI.
To get the opposite of slideUp and slideDown. Add these two functions to jQuery.
$.fn.riseUp = function() { $(this).show("slide", { direction: "down" }, 1000); }
$.fn.riseDown = function() { $(this).hide("slide", { direction: "down" }, 1000); }
I found a tricky way...
you can set div with css style bottom:0px,
add call
$("#div).slideDown();
will show with the slideUp-to-show effect you want.
Jquery toggle
This toggle effect is only for up and down. Jquery UI is for every other direction
For those who donĀ“t use the Jquery UI but want to add the function to Jquery Library:
jQuery.fn.slideUpShow = function (time,callback) {
if (!time)
time = 200;
var o = $(this[0]) // It's your element
if (o.is(':hidden'))
{
var height = o.css({
display: "block"
}).height();
o.css({
overflow: "hidden",
marginTop: height,
height: 0
}).animate({
marginTop: 0,
height: height
}, time, function () {
$(this).css({
display: "",
overflow: "",
height: "",
marginTop: ""
});
if (callback)
callback();
});
}
return this; // This is needed so others can keep chaining off of this
};
jQuery.fn.slideDownHide = function (time,callback) {
if (!time)
time = 200;
var o = $(this[0]) // It's your element
if (o.is(':visible')) {
var height = o.height();
o.css({
overflow: "hidden",
marginTop: 0,
height: height
}).animate({
marginTop: height,
height: 0
}, time, function () {
$(this).css({
display: "none",
overflow: "",
height: "",
marginTop: ""
});
if (callback)
callback();
});
}
return this;
}
Credits: #redbmk answer
Despite the name, slideDown can actually slide your element both ways. Use absolute position if it is required to animate inside the parent element:
#slideup {
position:fixed;
bottom:0;
background:#0243c9;
color:#fafefa;
width:100%;
display:none;
padding: 20px;
}
#littleslideup {
position:absolute;
bottom:0;
background:#000;
color:#fff;
display:none;
padding:10px;
z-index:100;
}
#slidedown {
position:fixed;
top:0;
background:#c94333;
color:#fafefa;
width:100%;
display:none;
padding: 20px;
}
button {
display:inline-block;
font-size:16px;
padding:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="position:relative">This amounts to 70% of the total timber stand area of the region (not including the dwarf pine and shrubby alder) and is more than the total area of all other stone birch forests growing in the Magadan, Khabarovsk, Primorye and Sakhalin regions and other areas of its distribution.
<div id="littleslideup">Absolute-positioned element</div>
</div>
<span style="color:red">Click >> </span>
<button onclick="jQuery('#slideup').slideDown(1500);" >"Slideup"</button>
<button onclick="jQuery('#slidedown').slideDown(1500);" >"Slidedown"</button>
<button onclick="jQuery('#littleslideup').slideDown(1500);">"Slideup" inside element</button>
<div>Finally, closing the subject of volcanic activity, it must be said that the stone birch stands by its functional reaction quite adequately in order to re ect the character and intensity of the physical, chemical and thermic processes, stipulated by volcanism as well as the in uence upon biota and ecosystems.</div>
<div id="slideup">Could be a bottom cookie warning bar</div>
<div id="slidedown">Could be a top cookie warning bar</div>
I've got some downvotes so I checked my answer and indeed I didn't answered correctly the OP question, sorry. So I'm gonna try to fix that.
First, the slideUp() method in JQuery is intended to hide the element rather than reveal it. It is basically the opposite of slideDown() which shows your element by sliding it down.
By knowing that I think we agree that there is no magic function right there to do a slide up effect to show an element (in JQuery).
So we need to do a little bit of work to get what we need: slid up reveal effect. I found out some solutions and here is one I think simple to implement:
https://coderwall.com/p/9dsvia/jquery-slideup-to-reveal
The solution above works with the hover event, for the click event try this modified code:
http://jsfiddle.net/D7uT9/250/
The answer given by #redbmk is also a working solution.
Sorry for my misunderstanding the first time.
OLD ANSWER
It's an old post, but if someone is looking for a solution here is my recommandation.
We can, now, use slideToggle() to achieve this effect (without the need of jQuery UI).
$(".btn").click(function () {
$("div").slideToggle();
});
Documentation: http://api.jquery.com/slidetoggle/
Having encountered this with a student looking to "slide up always hide" an error container, I advised he simply use CSS transitions:
.slide-up {
transition: 1s ease-out;
transform: scale(1);
}
.slide-up[aria-hidden="true"] {
transform: scale(0);
height: 0;
}
jQuery(document).ready(function($) {
const $submitButton = $(".btn");
const $someDivs = $("div");
const $animatedSlidingTargets = $(".slide-up");
$someDivs.on("click", function() {
$animatedSlidingTargets.attr("aria-hidden", true);
});
});
For #Jason's answer, whether slide-up to show and slide-down to hide, you still need to use the { direction: "down" } option in jQuery:
$(".btnAbout").on("click", function () {
// Slide-up to show
$("#divFooter").show("slide", { direction: "down" }, 1000);
});
$("#btnCloseFooter").on("click", function () {
// Slide-down to hide
$("#divFooter").hide("slide", { direction: "down" }, 1000);
});
But this requires jquery-ui, or else you'll hit the TypeError: something.easing[this.easing] is not a function error:
<script defer src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>

Categories

Resources