How to convert a CSS and a javascript to a class - javascript

I have some problems converting the CSS id to a class and the javascript to match it. I need to use the script multiple times on the site
Here my code:
CSS:
#first {
background-color: #FFF;
width: auto;
height: auto;
overflow: hidden;
padding: 10px;
}
JavaScript:
var divh = document.getElementById('first').offsetHeight;
//keep default height
var divh = $("#first").outerHeight();
document.getElementById("first").style.height = "100px";
//toggle functions
$('div:first').toggle(
function () {
$("#first").stop().animate({
height: divh +'px'
}, 1000);
},
function () {
$("#first").stop().animate({
height: '100px'
}, 1000);
}
)

If I understand correctly you can just do:
.first {
background-color: #FFF;
width: auto;
height: auto;
overflow: hidden;
padding: 10px;
}
And the Javascript would be something like this:
var divh = $('.first').offsetHeight;
//keep default height
var divh = $(".first").outerHeight();
$('.first').style.height = "100px";
//toggle functions
$('div:first').toggle(
function () {
$(".first").stop().animate({
height: divh +'px'
}, 1000);
},
function () {
$(".first").stop().animate({
height: '100px'
}, 1000);
}
)
Just uses the jQuery selector to select the class instead of the ID.

I think you can use a "class selector" to get all the elements belonging to that class and then apply animation to all of them or one by one by using the each function (see here). Something like:
CSS
.first {
background-color: #FFF;
width: auto;
height: auto;
overflow: hidden;
padding: 10px;
}
JavaScript:
$('.first').each(function () {
var divh = $(this).outerHeight();
ecc. ecc.
})

use .first instant of #first

Mark's answer is almost entirely correct.
Although, he changed $('div:first') to $('div.first') which are not the same thing.
:first is part of jQuery selectors to select only the first matched element (see here).
So, if you want to pick the first div, use $('div:first'). If you want to select all divs with the "first" class, use $('div.first').

Related

Add/remove class with jQuery based on scroll

So basically I'd like to remove the class from header after the user scrolls down a little and add another class to it. Trying to figure out the simplest way of doing this but I can't make it work here is the code
$(function() {
var $sectionBox = $(".J_section-box"),
$navbarBox = $(".J_nav-bar-con"),
navHeight = $(".J_nav-bar-con").height();
$(window).on("scroll", function() {
$(window).scrollTop() >= $sectionBox.offset().top - navHeight ? $navbarBox.addClass("J_fixNavbar") : $navbarBox.removeClass("J_fixNavbar")
});
});
For simplicity, I would suggest to use toggleClass, what makes it a bit easier and better to maintain.
$(function() {
var $navbarBox = $(".J_nav-bar-con");
var navHeight = $(".J_nav-bar-con").height();
$(window).on("scroll", function() {
$navbarBox.toggleClass("J_fixNavbar", $(this).scrollTop() >= $(".J_section-box").offset().top - navHeight);
});
});
.content {
width: 100%;
height: 10000px;
}
.J_nav-bar-con {
width: 100%;
height: 100px;
background: gray;
position: fixed;
top: 0;
}
.J_section-box {
width: 100%;
height: 100px;
margin-top: 200px;
}
.J_fixNavbar {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="J_nav-bar-con"></div>
<div class="J_section-box"></div>
<div class="content"></div>

How can I make an element on hover?

All I'm trying to do is something like this mechanism:
Here is what I've tried so far:
$(document).ready(function(){
$('a').bind('mouseenter', function() {
var self = $(this);
this.iid = setInterval(function() {
var tag_name = self.text(),
top = self.position().top + self.outerHeight(true),
left = self.position().left;
self.append("<div class='tag_info'>Some explanations about"+tag_name+"</div>")
$(".tag_info").css({top: top + "px", left: left + "px"}).fadeIn(200);
}, 525);
}).bind('mouseleave', function(){
this.iid && clearInterval(this.iid);
});
});
body{
padding: 20px;
}
a {
color: #3e6d8e !important;
background-color: #E1ECF4;
padding: 2px 5px;
}
.tag_info{
position: reletive;
width: 130px;
height: 30px;
display:none;
background-color: black;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a>tag1</a>
<a>tag2</a>
As you see, it will be repeated every time. How can I execute it once per hover? And why the position doesn't apply?
Also is what I'm doing a right algorithm for such thing?
Thank you.
I am not sure why you are using setInterval but I think this should work. I removed setInterval and everytime the mouseenter event occurs we can append <div class='tag_info'> and every time mouseleave event occurs we can remove the the appended div.
$(document).ready(function(){
$('#test').bind('mouseenter', function() {
var self = $(this);
var tag_name = self.text(),
top = self.position().top + self.outerHeight(true),
left = self.position().left;
self.append("<div class='tag_info'>Some explanations about"+tag_name+"</div>")
$(".tag_info").css({top: top + "px", left: left + "px"}).fadeIn(200);
}).bind('mouseleave', function(){
$(this).children('.tag_info').remove();
});
});
body{
padding: 20px;
}
a {
color: #3e6d8e !important;
background-color: #E1ECF4;
padding: 2px 5px;
}
.tag_info{
position: reletive;
width: 130px;
height: 30px;
display:none;
background-color: black;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="test">tag1</a>
Like Dij said:
What you're doing:
setInterval - (repeats your function every 525ms)
What you want:
setTimeout - (executes your function once after 525ms delay)
Read more:
setInterval https://www.w3schools.com/jsref/met_win_setinterval.asp
setTimeout https://www.w3schools.com/jsref/met_win_settimeout.asp

vertical jquery accordion that will fill empty percentage when siblings collapse

Trying to get a jQuery vertical accordion working with 3 separate panels, A, B and C, each currently 33.3% wide. What I am trying to accomplish is when you collapse A, B & C will fill up the other 33% of that new available space from A being collapsed. If you close A & B then C would fill up 100% of the empty space. Any help is much appreciated as I am sure I may be approaching this the complete wrong way?
http://jsfiddle.net/Mvr3P/
HTML
<div id="toggle"><div id="toggle-button"></div></div>
<div id="toggle2"><div id="toggle-button2"></div></div>
<div id="toggle3"><div id="toggle-button3"></div></div>
CSS
#toggle {
float: left;
height: 200px;
width:33.3%;
background:red;
}
#toggle2 {
float: left;
height: 200px;
width:33.3%;
background:blue;
}
#toggle3 {
float: left;
height: 200px;
width:33.3%;
background:green;
}
#toggle-button {
height: 20px;
width: 100%;
background:blue;
}
#toggle-button2 {
height:20px;
width: 100%;
background: purple;
}
#toggle-button3 {
height:20px;
width: 100%;
background:orange;
}
JQUERY
$(document).ready( function(){
$('#toggle-button').click( function() {
var toggleWidth = $("#toggle").width();
if (toggleWidth = "33.3%") {
toggleWidth ="100%";
}
else if (toggleWidth = "100%") {
toggleWidth = "10px";
}
else {
toggleWidth = "33.3%"
}
$('#toggle').animate({ width: toggleWidth });
});
$('#toggle-button2').click( function() {
var toggleWidth = $("#toggle2").width();
if (toggleWidth = "33.3%") {
toggleWidth ="100%";
}
else if (toggleWidth = "100%") {
toggleWidth = "10px";
}
else {
toggleWidth = "33.3%"
}
$('#toggle2').animate({ width: toggleWidth });
});
$('#toggle-button3').click( function() {
var toggleWidth = $("#toggle3").width();
if (toggleWidth = "33.3%") {
toggleWidth ="100%";
}
else if (toggleWidth = "100%") {
toggleWidth = "10px";
}
else {
toggleWidth = "33.3%"
}
$('#toggle3').animate({ width: toggleWidth });
});
});
So there's a few tricky things going on here - the biggest challenge being how to animate more than one thing at a time.
JSFiddle of the solution here: http://jsfiddle.net/vYzpB/1/
Firstly, using classes to generically label your elements will allow you to write less code. This is a hugely important thing especially when you're applying the same behavior to more than one element. As you seem to know, you should only have one ID, but you can have many elements with the same class name.
<div class="accordion">
<div id="toggle" class="toggle-item"><div id="toggle-button" class="toggle-button"></div></div>
<div id="toggle2" class="toggle-item"><div id="toggle-button2" class="toggle-button"></div></div>
<div id="toggle3" class="toggle-item expanded"><div id="toggle-button3" class="toggle-button"></div></div>
</div>
Additionally, wrap all of the elements in a parent div (which I called accordion). I'll explain why shortly.
With that change, we can apply a click event to the .toggle-button class that handles the event for each of the accordion items:
$(document).ready( function(){
$('.toggle-button').click( function() {
// capture the parent div with the class of 'toggle-item'
var $parentToggle = $(this).parent('.toggle-item');
// run this within setTimeout so that both animations
// run at the same time. This is called "running asynchronously"
window.setTimeout(function() {
$('.toggle-item').not($parentToggle).animate({
width: '10%'
});
}, 0);
$parentToggle.animate({
width: '80%'
});
});
});
The window.setTimeout is the secret sauce here. Without it, jQuery will wait until the first animation is finished, THEN move on to the next. By wrapping the first animation inside a setTimeout we essentially remove it from the top-to-bottom execution process and call it asynchronously. We set this to timeout at "0" because we actually want it to run right away (as opposed to waiting a certain amount of milliseconds).
The CSS
The CSS has a "default state" .expanded class we add to the element intended to take up the 2/3 (or whatever % you want) space.
Notice also how that new parent div has a set width. Without it, the elements will flop around while transitioning.
.accordion {
width: 600px;
overflow: hidden;
}
.toggle-item {
float: left;
height: 200px;
width: 10%;
}
.expanded {
width: 80%;
}
#toggle {
background:red;
}
#toggle2 {
background:blue;
}
#toggle3 {
background:green;
}
.toggle-button {
height: 20px;
width: 100%;
}
#toggle-button {
background:blue;
}
#toggle-button2 {
background: purple;
}
#toggle-button3 {
background:orange;
}

Animating multiple divs by switching their classes

i am having a hard time trying to animate this box, so the changes go smooth, but i just cannot figure out how to keep everything together. Help would be really appreciated. (already tried with 'switchClass') Here is the whole code:
<script src="jquery.js"></script>
<script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<style>
#box {
position: relative;
margin: auto;
padding: auto;
display: block;
width: 167px;
height: 167px;
}
#box .item {
position: relative;
margin: 0;
display: block;
width: 100%;
height: 33%;
cursor: pointer;
}
#box .over {
height: 84%;
}
#box .other {
height: 8%;
}
#top {
background: red;
}
#mid {
background: green;
}
#bot {
background: blue;
}
</style>
<script>
function anim(item) {
$('.item').attr('class', 'item other');
$('#' + item.id).attr('class', 'item over');
}
function clean() {
$('.item').attr('class', 'item');
}
</script>
<div id='box' onmouseout="clean()">
<div id='top' class='item' onmouseover='anim(this)'></div>
<div id='mid' class='item' onmouseover='anim(this)'></div>
<div id='bot' class='item' onmouseover='anim(this)'></div>
</div>
edit: this code is running just fine, but its just an example of final output (just some animations needed)
Maybe this is not super cool, but seems to do job:
var $items = $('.item').on({
mouseover: function () {
$items.removeClass('over other');
$items.stop().filter(this).animate({height: '84%'}, function () {
$(this).addClass('over');
})
.end().not(this).animate({height: '8%'}, function () {
$(this).addClass('other');
});
},
reset: function() {
$items.removeClass('over other').stop().animate({height: '33%'});
}
});
$('#box').mouseout(function() {
$items.trigger('reset');
});
http://jsfiddle.net/dfsq/4vnkh/1/
If you want to animate the change, please take a look at jQuery animate
Something like this:
$('.item').mouseenter(function() {
$('.item').animate({
height: 80%
}, 500, function() {
// Animation complete.
});
});
$('.item').mouseleave(function() {
$('.item').animate({
height: 33%
}, 500, function() {
// Animation complete.
});
});
in this case you don't need onmouseout or onmouseover
If your animation is based solely on CSS class attributes why not use CSS3 hover pseudo-selector?
Example:
.box {
width: 200px;
}
.box:hover {
width: 400px;
}
<div class="box">Hover over me!</div>
Additional: Response to comments
If you are looking for custom animation duration you can use a callback function with a duration for the initial function call. Here's an example:
$('#div').animate({
width: '200px',
color: 'blue'
}, 5000, function() {
// Animation finished after 5 seconds.
alert("Animation complete!");
});
Addition #2
Your problem child is this little guy:
$('.item').attr('class', 'item other');
This sets each box to 8% height and THEN expands the primary animating box. Remove this and your #box will remain the same height throughout all animations!

How to toggle (hide / show) sidebar div using jQuery

I have 2 <div>s with ids A and B. div A has a fixed width, which is taken as a sidebar.
The layout looks like diagram below:
The styling is like below:
html, body {
margin: 0;
padding: 0;
border: 0;
}
#A, #B {
position: absolute;
}
#A {
top: 0px;
width: 200px;
bottom: 0px;
}
#B {
top: 0px;
left: 200px;
right: 0;
bottom: 0px;
}
I have <a id="toggle">toggle</a> which acts as a toggle button. On the toggle button click, the sidebar may hide to the left and div B should stretch to fill the empty space. On second click, the sidebar may reappear to the previous position and div B should shrink back to the previous width.
How can I get this done using jQuery?
$('button').toggle(
function() {
$('#B').css('left', '0')
}, function() {
$('#B').css('left', '200px')
})
Check working example at http://jsfiddle.net/hThGb/1/
You can also see any animated version at http://jsfiddle.net/hThGb/2/
See this fiddle for a preview and check the documentation for jquerys toggle and animate methods.
$('#toggle').toggle(function(){
$('#A').animate({width:0});
$('#B').animate({left:0});
},function(){
$('#A').animate({width:200});
$('#B').animate({left:200});
});
Basically you animate on the properties that sets the layout.
A more advanced version:
$('#toggle').toggle(function(){
$('#A').stop(true).animate({width:0});
$('#B').stop(true).animate({left:0});
},function(){
$('#A').stop(true).animate({width:200});
$('#B').stop(true).animate({left:200});
})
This stops the previous animation, clears animation queue and begins the new animation.
You can visit w3school for the solution on this the link is here and there is another example also available that might surely help,
Take a look
The following will work with new versions of jQuery.
$(window).on('load', function(){
var toggle = false;
$('button').click(function() {
toggle = !toggle;
if(toggle){
$('#B').animate({left: 0});
}
else{
$('#B').animate({left: 200});
}
});
});
Using Javascript
var side = document.querySelector("#side");
var main = document.querySelector("#main");
var togg = document.querySelector("#toogle");
var width = window.innerWidth;
window.document.addEventListener("click", function() {
if (side.clientWidth == 0) {
// alert(side.clientWidth);
side.style.width = "200px";
main.style.marginLeft = "200px";
main.style.width = (width - 200) + "px";
togg.innerHTML = "Min";
} else {
// alert(side.clientWidth);
side.style.width = "0";
main.style.marginLeft = "0";
main.style.width = width + "px";
togg.innerHTML = "Max";
}
}, false);
button {
width: 100px;
position: relative;
display: block;
}
div {
position: absolute;
left: 0;
border: 3px solid #73AD21;
display: inline-block;
transition: 0.5s;
}
#side {
left: 0;
width: 0px;
background-color: red;
}
#main {
width: 100%;
background-color: white;
}
<button id="toogle">Max</button>
<div id="side">Sidebar</div>
<div id="main">Main</div>
$('#toggle').click(function() {
$('#B').toggleClass('extended-panel');
$('#A').toggle(/** specify a time here for an animation */);
});
and in the CSS:
.extended-panel {
left: 0px !important;
}
$(document).ready(function () {
$(".trigger").click(function () {
$("#sidebar").toggle("fast");
$("#sidebar").toggleClass("active");
return false;
});
});
<div>
<a class="trigger" href="#">
<img id="icon-menu" alt='menu' height='50' src="Images/Push Pin.png" width='50' />
</a>
</div>
<div id="sidebar">
</div>
Instead #sidebar give the id of ur div.
This help to hide and show the sidebar, and the content take place of the empty space left by the sidebar.
<div id="A">Sidebar</div>
<div id="B"><button>toggle</button>
Content here: Bla, bla, bla
</div>
//Toggle Hide/Show sidebar slowy
$(document).ready(function(){
$('#B').click(function(e) {
e.preventDefault();
$('#A').toggle('slow');
$('#B').toggleClass('extended-panel');
});
});
html, body {
margin: 0;
padding: 0;
border: 0;
}
#A, #B {
position: absolute;
}
#A {
top: 0px;
width: 200px;
bottom: 0px;
background:orange;
}
#B {
top: 0px;
left: 200px;
right: 0;
bottom: 0px;
background:green;
}
/* makes the content take place of the SIDEBAR
which is empty when is hided */
.extended-panel {
left: 0px !important;
}

Categories

Resources