Creating a toggle on click - javascript

I am trying in jQuery to click a link and the content within it then comes in to 0px from the right of the screen. Then when you click it again, It closes, a kind toggle effect.
My current jQuery is:
$('.bet-slip-outer').click(function() {
// Responsive Stuff...
var windowwidth = $(window).width();
$('.bet-slip').animate({
'right': '-240px'
});
}, function() {
$('.bet-slip').animate({
'right': '0px'
});
});
However when I click the .bet-slip the right:-240 just seems to take precedence.
What am I doing wrong?
Cheers

with conditional:
define right style.
<div class="bet-slip" style="right:0px;"></div>
jquery
$('button').click(function() {
if($('.bet-slip').css('right') === '0px' ){
$('.bet-slip').animate({'right':'-240px'});
} else {
$('.bet-slip').animate({'right':'0px'});
}
});
other
only style:
$('button').click(function(){
$('div').toggleClass('right');
});
div{
position:relative;
width:100px;
height:10px;
background:green;
right:-100px;
transition:1s;
}
.right{
right:0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
</div>
<button>
f
</button>

Use a variable to check if the element has been clicked yet.
toggle = "on";
$('.bet-slip-outer').click(function() {
// Responsive Stuff...
var windowwidth = $(window).width();
if(toggle == "on"){
$('.bet-slip').animate({
'right': '0px'
});
toggle = "off";
}else{
$('.bet-slip').animate({
'right': '-240px'
});
}
});

According to the official documentation, the .click() method only accepts a single handler. You cannot declare two different handlers for that purpose. There are two solutions to that — one is to delegate the animation to CSS, and use .toggleClass() instead, or to use stateful code:
Store the toggle status of the element in its own jQuery data object
Read the data object. If it doesn't exist or is 0, do something (condition 1)
If it exists and is 1, do something else (condition 2)
You can of course modify the binary conditions 1 and 2 into the effect you want to achieve.
In addition, in order to prevent jerky animation due to rapid clicking/toggling, you should stop the animation before you more animations to the queue. This is done by chaining .stop(true, true) to the object.
$(function() {
$('.bet-slip-outer').click(function() {
// Check state
if(!$(this).data('toggle') || $(this).data('toggle') == 0) {
$(this).data('toggle', 1);
$('.bet-slip').stop(true, true).animate({
'right': '-240px'
});
} else {
$(this).data('toggle', 0);
$('.bet-slip').stop(true, true).animate({
'right': '0'
});
}
});
});
.bet-slip {
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bet-slip-outer">
<div class="bet-slip">bet-slip</div>
</div>

QUITE HARDING-CODING STYLE VARIABLES IN JS!
You could do something like:
$( ".bet-slip-outer .bet-slip" ).toggleClass( "animation" );
Then in your CSS you would do:
.bet-slip-outer .bet-slip { right: 0px;}
.animation { right: -240px;}
Why to use this option over others?
Your not hard-coding STYLE variables in your java-script your leaving that to CSS (what it's made for). As the project grows if you keep hard-coding it will eventually make your JS code base 'smell.' IE: I pain to change down the road!

Related

How to animate navigation bar with jquery

I am creating a navigation bar see my fiddle: https://jsfiddle.net/dfbwp71u/
when I uses css() its working properly but when I use animate() its not giving me the result.
my html:
<nav class="navigation navbar-fixed-top">
</nav>
jquery:
$(window).scroll(function(){
// these conditional statements are working fine
if($(window).scrollTop() > 5)
{
$('.navigation').css({
'background-color':'#000'
});
}
else
{
$('.navigation').css({
'background-color':'#eee'
});
}
});
When I replace the .css() to animate() it stops giving me the result.
// ???
$('.navigation').animate({
'background-color':'#000'
});
Well you don't need animate for this unless you are not satisfied with css transition
DEMO
What I would do is just add a class called fixed and assign background-color:#000 like one below:
.fixed{
background-color:#000
}
and then I'll toggle this class based on the condition as below:
$(window).scroll(function(){
if($(window).scrollTop() > 5)
{
$('.navigation').addClass('fixed');
}
else
{
$('.navigation').removeClass('fixed');
}
});
The main thing we need to add here is transition property to .navigation and it will take care of rest:
.navigation
{
min-height:100px;
max-width:100%;
background-color:#eee;
transition: background 500ms;//change time accordingly
}
According to http://api.jquery.com/animate/
All animated properties should be animated to a single numeric value,
except as noted below; most properties that are non-numeric cannot be
animated using basic jQuery functionality (For example, width, height,
or left can be animated but background-color cannot be, unless the
jQuery.Color plugin is used)
so either use jquery-ui or jQuery.Color plugin
Add Jquery UI if you not add and change css property name 'background-color' to 'backgroundColor',
$(window).scroll(function(){
if($(window).scrollTop() > 5)
{
$('.navigation').animate({backgroundColor:'#eee'});
}
else
{
$('.navigation').animate({backgroundColor:'#000'});
}
});

How can I hide a button when scrolled to the top of a page?

I'm trying to adapt this JSFiddle to make the menu button on my website hide when I'm at the top of the page and show when I start scrolling down.
I modified the JS to match the CSS on my site. Then I placed it in tags in the head of my page
var $scb = $('<div class="toggle-menu-wrap"></div>');
$('.top-header').append($scb);
var $ccol = $('.content');
$ccol.scroll(function(){
$scb.stop(true,true).fadeTo(500, $ccol.scrollTop() > 10 ? 1 : 0);
});
However, it still doesn't work. Am I making a mistake in how I'm modifying the JS to fit my CSS?
You can include the toggle-menu-wrap element in your HTML from the start. There is no need to insert it using JS.
Write the one line of CSS you need, which is to hide the element from the beginning
.toggle-menu-wrap {
display: none;
}
Your version of jQuery uses 'jQuery' instead of '$' to reference itself. I would also re-write your JS like:
jQuery(document).ready(function() {
fadeMenuWrap();
jQuery(window).scroll(fadeMenuWrap);
});
function fadeMenuWrap() {
var scrollPos = window.pageYOffset || document.documentElement.scrollTop;
if (scrollPos > 300) {
jQuery('.toggle-menu-wrap').fadeIn(300);
} else {
jQuery('.toggle-menu-wrap').fadeOut(300);
}
}
Like #murli2308 said in the comments above, you need to attach a scroll event listener to the window:
$(document).ready(function () {
var $scb = $('<div class="scroll-border"></div>');
$('.above').append($scb);
var $ccol = $('.content');
$(window).scroll(function(){
$scb.stop(true,true).fadeTo(500, $ccol.scrollTop() > 10 ? 1 : 0);
});
})
Wrapping your code in $(document).ready() would also be a good idea.
The reason $ccol.scroll(function() { ... works in that fiddle is because of the CSS:
.content{
height: 200px;
width: 200px;
overflow: auto;
}
Notice overflow: auto;. This causes that specific div to be scrollable. However, on your website, you scroll the entire page, not $ccol. This means the event handler will never fire a scroll event (since $ccol will never scroll).
You might have forgotten to link Jquery.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
Link this inside your head tag incase.....
This should do the job:
$(window).scroll(function(e){
if ($(this).scrollTop() > 0) {
$(".your_element").css("display", "block");
} else {
$(".your_element").css("display", "none");
}
});

jQuery slider doesn't loop perfectly

Im currently having a problem with my background image slider. It works perfectly fine the first time it runs, but the second time it 'bumps' the picture to the right when visible, instead of doing that when not visible. I hope some of you would take the time to look into this. Would be appreciated.
The code I'm using :
html part:
<div id="logo">
<img src="images/5.jpg">
<img src="images/6.jpg">
<img src="images/7.jpg">
<img src="images/8.jpg">
<img src="images/9.jpg">
<img src="images/10.jpg">
<img src="images/11.jpg">
</div>
css part:
#logo img {
min-height: 100%;
width:110%;
height: 100%;
position: fixed;
top:0px;
left: 0px;
}
JavaScript:
var slideshow = 0;
var currentImageIndex = 0;
var nextImage = function () {
var $imgs = $('#logo > img');
currentImageIndex++;
if (currentImageIndex > $imgs.length) {
currentImageIndex = 1;
}
$('#logo > img:nth-child(' + currentImageIndex + ')')
.fadeIn(function () { //.fadeIn() .show()
$(this).animate({
left: '-75px'
}, 8000, 'linear')
$(this).delay(100).fadeOut(nextImage), 1200; //.fadeOut() .show()
$(this).css({
left: '0px'
})
})
};
And it's triggered when clicked:
$( ".hexagoncontainer7" ).click(function() {
if (slideshow == 0) {
nextImage();
slideshow=1;
}
});
There are a few things to improve here. Hopefully this will give you a good start:
Currently, you're searching the DOM for your images twice upon each nextImage() call:
var $imgs = $('#logo > img'); and $('#logo > img:nth-child(' + currentImageIndex + ')').
Searching the DOM is computationally expensive, and you should do it only when necessary. Instead, if you need to work with the same elements over and over again (as you do with your images), select them once, and store them in variables for later use.
In the following lines:
$(this).animate({left: '-75px'}, 8000, 'linear')
$(this).delay(100).fadeOut(nextImage), 1200; //.fadeOut() .show()
$(this).css({left: '0px'})
a few things need to be fixed. First, line 3 removes any offset on your images left over from the previous pass. You want this step at the beginning of your sequence of steps (even before fadeIn), not at the end where its effect will be delayed.
Next, you do not need the delay(100) call before fadeOut(), because animate() lets you provide a callback which will be called once the animation completes. Supply your fadeOut code in the callback.
Also, notice that fadeOut first takes duration as a parameter, then the complete callback, i.e. your call should be fadeOut(1200, nextImage) if you want the fade-out effect to execute over 1200 ms.
Finally, jQuery lets you chain functions, which will save you a few calls to the jQuery function.
You should consider removing the click handler on #logo after the first click, to avoid unexpected behavior when users click more than once.
At the moment your images are stacked in reverse order over each other. You need to hide all but the first one with CSS.
Don't forget the semicolons and name your functions as actions, i.e. loadNextImage - your code will be easier to read.
Here is a working fiddle with all the changes: http://jsfiddle.net/stiliyan/4bo0258p/ (forked from the one isherwood posted)
In case you want to learn more best practices with jQuery I strongly recommend the Try jQuery course by CodeSchool.

Show hide div with animation

I made this script, which opens a div with the right class and close the others.
function showhide(id) {
if (document.getElementById) {
var divid = document.getElementById(id);
var divs = document.getElementsByClassName("hideable");
for (var i = 0; i < divs.length; i = i + 1) {
divs[i].style.display = "none";
}
divid.style.display = "block";
}
return false;
}
Is it possible to make some animation, like fadout, easeout instead of just showing it by display options?
You could try this
function showhide(id) {
if (document.getElementById) {
var divid = document.getElementById(id);
var divs = document.getElementsByClassName("hideable");
for (var i = 0; i < divs.length; i = i + 1) {
$(divs[i]).fadeOut("slow");
}
$(divid).fadeIn("slow");
}
return false;
}
Have a look at this fiddle "http://jsfiddle.net/9jtd3/"
There are many more techniques provided by Jquery library, You should have a look at that too.
You can use slideDown() and slidUp() of jQuery
$( document.body ).click(function () {
if ( $( "div:first" ).is( ":hidden" ) ) {
$( "div" ).slideDown( "slow" );
} else {
$( "div" ).slideUp("slow");
}
});
This example will toggle multiple elements with the same class name. This example does not need jquery.
HTML:
<button onclick="fadeInAndOut(this)" style="width:100%">Toggle 1</button>
<div class="accordianPanel acordianPanelHidden accordianPanelStyle">Panel 1</div>
<button onclick="fadeInAndOut(this)" style="width:100%">Toggle 2</button>
<div class="accordianPanel acordianPanelHidden accordianPanelStyle">Panel 2</div>
Javascript:
function fadeInAndOut(thz) {
var elmt = thz.nextElementSibling;//Get the element that is below the button that
//was just clicked
elmt.classList.toggle("acordianPanelHidden");//Toggle the class which changes
//attributes which triggers the `transition` CSS
}
CSS
.accordianPanel {
opacity: 1;
height:100%;
transition: all 1s;
}
.accordianPanel.acordianPanelHidden {
opacity: 0;
height: 0px;
visibility:hidden;/* This must be used or some strange things happen -
What happens is that even though the content of the panel is not shown
any buttons in the content can still be clicked -
So basically there are invisible buttons that can accidently get clicked -
if the visibility is not set to hidden - And the visibility doesn't need to be explicitly changed to visible
from hidden in order to show the content
because if visibility:hidden is not used then by default the content is
displayed -
*/
}
.acordianPanelShown {
height: 100%;
width: 100%;
opacity: 1;
}
.accordianPanelStyle {
background:red;
}
This will surely solve your problem.
You can use .fadeOut() directly if you have included jQuery library in your script.
This is way easier with only CSS.
You make a class
div {
display:block;
transition: all .2s ease-out;
}
.hidden {
display:none;
}
And with javascript, you apply or remove the class hidden when you want to. jQuery animation lib is wayyyy far from good to be used. It's clunky, and ressource eating for your user. CSS works with your GPU instead, allowing a more fluid animation.
If You are using Jquery then another way to do this is
function showhide(id) {
$(".hideable").fadeOut("slow");
$("#" + id).fadeIn("slow");
}
Assuming "hideable" as className in your group of divs
Good luck.
You can do that using a Library like jQuery or something.
You can sure make it using plain javascript, but there's no point doing that since jQuery is an amazing library.
See some examples of show and hide

Each element height if higher then function

Good day, I'm trying to figure out how to do small thing.
I have several elements on page that needs to checked on height and if height is higher, for example > 100, then I need to call function for them.
So far I came up to this:
var filterHeight = $('div.class').height();
if (filterHeight > 100) {
$('div.class').css('height', '100px');
$('div.class').css('overflow-y', 'scroll');
}
Problem with that as you know is that it will add those params to all element because I strictly point to that.
I guess it I will need to do something with .each(), but...
Thank you for your suggestions and help.
Because I can't answer my own question I'm updating here.
I used your solution and change it a little bit, instead adding inline css I added class that fetch css.
So what I did is:
1) When page loads
$('div.class').each(function() {
if ($(this).height() > 200) {
$(this).addClass('scroller');
}
});
.scroller {
height: 200px;
overflow-y: scroll !important;
}
So it checked all blocks with height more than 200px and adds class.
2) After I'm calling for Ajax/JOSN and it gives me new data for those blocks I was in need to check for those elements heigh changes. So on .ajax complete I removed class and check again.
complete: function () {
$('.box.refine .middle ul').removeClass('scroller')
$('.box.refine .middle ul').each(function() {
if ($(this).height() > 200) {
$(this).addClass('scroller');
}
});
}
Thats all.
You need to look at jQuery .each()
Something like:
$('.check-these').each( function(){
if ($(this).height() > 100) {
$(this).css('height', '100px');
$(this).css('overflow-y', 'scroll');
}
});
This isn't tested but should put you on the right track.
$('div.class').each(function(){
if($(this).height() > 100)
{
$(this).css({height: "100px", overflow-y: "scroll"});
}
});
Loop through the elements and check each individually:
$('div.class').each(function() {
if ($(this).height() > 100) {
$(this).css('height', '100px').css('overflow-y', 'scroll');
}
});
But why not just put that in the css to begin with?
div.class {
height: 100px;
overflow-y: scroll;
}

Categories