.toggle only working on the second click

I’m working on a full image background website where the visitor has the opportunity to hide the content to see the background image in full. The problem I have is that when the page is loaded and the toggle button is clicked, the function isn’t executed. Only after I click a second time the function is executed. What do I need to change to make the function work on the first click. This is the function I am using:


jQuery(function($) {
    $(document).ready(function() {
        $('.panelHandle').toggle(function() {
            $('#content').stop(true, false).animate({
                'left': '260px'
            }, 900);						
        }, function() {
            jQuery.noConflict();
        });

        jQuery('.panelHandle').toggle(function() {
            // Do nothing
        }, function() {

            jQuery.noConflict();
            jQuery('#content').animate({
                left: '-320px'
            }, 500);						

        });
    });
});

Can anyone please tell me what I need to change to make this event work on the first click.

Thank you in advance!!

Hi,

Can you post a link to the page in question?
Shouldn’t be too hard to figure out.

Hi Pullo thank you so much for your reaction. The direct link to the page you find here!. Thank you in advance for your help

No problem donboe,

I have rewritten your functions.js file for you.

Delete all of the code that is in there and replace it with this:

// JavaScript Document
$(window).load(function() {   
  var theWindow = $(window),
  $bg = $("#bg"),
  aspectRatio = $bg.width() / $bg.height();

  function resizeBg() {
    if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
      $bg.removeClass().addClass('bgheight');
    } else {
      $bg.removeClass().addClass('bgwidth');
    }
  }

  theWindow.resize(function(){resizeBg();}).trigger("resize");
});

$(document).ready(function(){
  $('#content').tinyscrollbar();  
  
  var c = $('#content').width();
  $('.panelHandle').toggle(function() {
    $('#content').animate({left: '-=' + c}, 900);
  }, function() {
    $('#content').animate({left: '+=' + c}, 500);
  });
});

This will also solve your original problem.
Please let me know if everything still works as expected.

Hi Pullo. Thank you so much for the reply and the modification of the Javascript. It is working like a charm. I was wondering if I could do the same with multiple divs? What I mean is that I would like to have multiple divs that will slide from left to right based on the menu choice. So when a button in the menu is pressed, the div (id) corresponding with that button will slide from left to right(open) but not before the div that was open already, has slide from right to left(close). Is this possible and if so, is it very difficult to accomplish.

Thank you in advance

Hi donboe,

No worries, glad I could help!

If you want to apply this behaviour to multiple divs, it shouldn’t be too difficult.

You would need to apply the same class e.g. “slider” to all divs that should be animated.
You would then get a reference to all of them using $(".slider"). This will returnan array of jQuery objects.
You can then loop through the array using [each](http://api.jquery.com/jQuery.each/) and attach the required behaviour to each of them.
In the callback you can reference the particular div using $(this), so it would look something like this:

$('.slider').each(function(){
  $(this).click(function () {
    do stuff ...
  })
});

From within the callback, you can reference the appropriate elements using sibling, child and parent selectors, as appropriate.

The only tricky part will be queueing up the animations (i.e. wating for one to finish, before the next one starts).
My first idea would be to use animate’s “on completion” call back in some way, but I myself would have to do a little research into this.

Why don’t you make a start with the tips I gave you, then let me know how you get on.
I’ll be happy to help you get this working.

Hi Pullo. Thank you so much for your explanation and patience. I tried what you said but I lost it with the part about the looping (each). This is way behind my knowledge. Are there not any plug-inns where all these behaviors are combined. Or can you give a simple example of how that each function is working.

Thank you in advance.

No problem donboe,

Regarding plugins:
You could look here: http://www.jquery4u.com/plugins/10-jquery-panel-slider-plugins/
Or here: http://www.jqeasy.com/jquery-slide-panel-plugin/

Saying that, this is something that shouldn’t be too difficult to code ourselves.
If you make me a very simple template with three panels on it that should slide in and out when clicked, I’ll use that to code you up an example.

HTH

I made a temporary template which you can find here. What I have done is the following. I made a centered wrapper, holding the menu and a div called mask. Within the mask div I have 3 content divs (index, about and contact) The mask div has overflow hidden so the divs inside are hidden when sliding. All divs have the same class .slider.I added the jQuery plugin but couldn’t figure what to do with the callback you mentioned earlier.

I hope I don’t ask to much

Hi Pullo. I just found this example. It is a bit of what I want. I tried some things using the structure as they have it, but I couldn’t get it to work. I simply couldn’t figure how they load the content. I tried it with own content pages e.a.


        <h3><a href="contact-us.html" class="slideout" id="show-contact">Contact us</a></h3>
        <div></div>

But it isn’t showing at all. I couldn’t find those id’s e.a. show-contact in one of the jQuery files either

Hey donboe,

You beat me to it by a few seconds.
I’ve just finished making an example for you: http://hibbard.eu/blog/pages/silder-demo/

Is that roughly what you are after?

That is one word blilliant Pullo. That is indeed where I’m after. I’m gonna have a look and come back about it later if that is okay.

Edit: Like I said in one word brilliant. Thank you so much!!! I have one last question though. Lets say I also want to give the opportunity to just hide the content panel. Can I simply add a toggle to the panel and use the function as in your second reply:

$(document).ready(function(){
var c = $(‘Content’).width();
$(‘.panelHandle’).toggle(function() {
$(‘Content’).animate({left: ‘-=’ + c}, 900);
}, function() {
$(‘Content’).animate({left: ‘+=’ + c}, 500);
});
});

No problemo :slight_smile:

One detail which we musn’t forget however, is what we want to do if the user clicks on multiple links (i.e. home, about, contact) in rapid succession.
Currently this confuses the script somewhat …

Hi Pullo. I’m not sure if I can continue on this post or that I should start a new one, but my next question has to do with the previous one so I give it a try. I am working on a full image background website and I was wondering if it is possible to change the background image when I click on the various tabs. Since there is already a function trickerd when I click the various tabs, I’m really getting confused.

This is what I normally use for the 100% width 100% height background:

CSS


#bg {
	position: fixed;
	top: 0;
	left: 0;
	z-index: -999;
}

.bgwidth {
	width: 100%;
}

.bgheight {
	height: 100%;
}

Javascript


$(window).load(function() {

        var theWindow        = $(window),
            $bg              = $("#bg"),
            aspectRatio      = $bg.width() / $bg.height();

        function resizeBg() {

                if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
                    $bg
                        .removeClass()
                        .addClass('bgheight');
                } else {
                    $bg
                        .removeClass()
                        .addClass('bgwidth');
                }

        }

        theWindow.resize(function() {
                resizeBg();
        }).trigger("resize");

});

Thank you again in advance!

Hi donboe,

I just had a look for the background images on your server (re. your PM) and couldn’t find them.
Could you provide links and I will update my example.

In this case simply set the duration of the animation to zero.

i.e.

$(document).ready(function(){
  var c = $('#content').width();
  $('.panelHandle').toggle(function() {
    $('#content').animate({left: '-=' + c}, 0);
  }, function() {
    $('#content').animate({left: '+=' + c}, 0);
  });
});

Hey donboe,

I found the background images and updated the demo for you.
You can find it here: http://hibbard.eu/blog/pages/sliding-panels-with-backgrounds/

I think you’ll find this does everything you want :slight_smile:
I cheated and used the jQuery Backstretch plugin to sort the backgrounds out for me, but you should be able to adapt quite easily.

I hope that helps you.

Hi Pullo. This is great. Works really as I wanted. You made me a happy person. I have two questions left. The first one is about the path to the background photos. As I have it now the are in the root on my server. How can I have them coming from a separate folder e.a. page_photos. The second question is about manually closing and opening the content panel. I have added the function as described in the quote above and I added a <li><a href:></a></li> with the class panelHandle to the menu. Furthermore did I add a class to the various divs called .content which have a width of 500px. When I click that tab, the content is indeed closing but won’t open again and the menu isn’t longer functioning. What am I doing wrong? This is really going going way behind my knowledge. This is what I have sofar:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" class="bg-size">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
* {/* Demo only */
	margin: 0;
	padding: 0;
}

html, body {
	width: 100%;
	height: 100%;
}

body:before {
	content:"";
	height:100%;
	float:left;
	width:0;
	margin-top:-32767px;
}

#wrapper {
	width: 1024px;
	min-height: 100%;
	margin: 0 auto;
	position: relative;
}

* html #wrapper { 
	height:100% 
}

#wrapper:after{
	content:" ";
	height:1%;
	display:block;
	clear:both;
	overflow:hidden;	
}

#wrapper #menu_panel {
	width: 274px;
	position: absolute;
	top: 0;
	bottom: 0;
	left: 0;
	background: #FF0000;
}

#wrapper #menu_panel #menu {
	width: 226px;
	margin: 80px 24px 20px;
}

#wrapper #menu_panel #menu li {
	width: 100%;
	line-height: 24px;
}

#wrapper #menu_panel #menu li a {
	color: #FFF;
	text-decoration: none;
}

#wrapper #mask {
	width: 750px;
	position: absolute;
	overflow: hidden;
	top: 0;
	bottom: 0;
	left: 274px;
}
	
#index,
#about,
#contact {
	width: 750px;
	padding-bottom: 30px; 
	position: relative;
	z-index: 9; 
	background: #0000FF; 
	color: #FFF; 
}

#index h2,
#about h2,
#contact h2 {
	padding: 20px;
}

#index p,
#about p,
#contact p {
	margin: 0 20px;
}

#index p + p,
#about p + p,
#contact p + p {
	margin: 15px 20px 0;
}

#about,
#contact {
	display: none; 
}

.content {
	width: 500px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-backstretch/2.0.3/jquery.backstretch.min.js"></script>
</head>

<body>
<div id="wrapper">

	<div id="menu_panel">
  	<ul id="menu">
			<li><a href="#index">Home</a></li>
      <li><a href="#about">About</a></li> 
      <li><a href="#contact">Contact</a></li>
      <br /><br />
      <li><a href="#" class="panelHandle">Show/Hide Content</a></li>   
  	</ul>
  </div>
  
  <div id="mask">
		<div id="index" class="slider sel content">
    	<h2>Homepage</h2>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed elit diam, suscipit in venenatis at, vestibulum et ligula. Integer molestie fermentum risus ut consequat. Fusce vulputate viverra enim vel commodo. Pellentesque pulvinar malesuada nibh at lacinia. Morbi cursus felis ut velit porta a ornare nulla aliquet. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vivamus quam dolor, mattis vel auctor ut, sollicitudin sed libero. Vivamus mollis convallis pellentesque. Quisque nunc odio, varius vulputate vestibulum sit amet, posuere vitae justo. Curabitur eu elit eu neque porttitor adipiscing sit amet in lacus. Nulla ac risus eget ligula fringilla malesuada. Phasellus ultrices luctus risus placerat vestibulum. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam pretium molestie lobortis.</p> <p>Nulla erat libero, euismod id porttitor sit amet, cursus id lectus. Sed id ante id dui dignissim semper eu at risus. Sed eleifend placerat elementum. Etiam consequat faucibus mauris, in tristique tellus egestas ac. Nam eu odio eget lorem vulputate vulputate. Proin ut velit vitae metus sollicitudin pulvinar et at mi. Maecenas pulvinar, dui vitae pellentesque interdum, lorem enim porta ligula, in lobortis turpis justo dapibus nibh. Pellentesque ultricies tellus tellus. Aliquam erat volutpat.</p> 
    </div>
    
   	<div id="about" class="slider content">
    	<h2>About Us</h2>
    	<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed elit diam, suscipit in venenatis at, vestibulum et ligula. Integer molestie fermentum risus ut consequat. Fusce vulputate viverra enim vel commodo. Pellentesque pulvinar malesuada nibh at lacinia. Morbi cursus felis ut velit porta a ornare nulla aliquet. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vivamus quam dolor, mattis vel auctor ut, sollicitudin sed libero. Vivamus mollis convallis pellentesque. Quisque nunc odio, varius vulputate vestibulum sit amet, posuere vitae justo. Curabitur eu elit eu neque porttitor adipiscing sit amet in lacus. Nulla ac risus eget ligula fringilla malesuada. Phasellus ultrices luctus risus placerat vestibulum. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam pretium molestie lobortis.</p> <p>Nulla erat libero, euismod id porttitor sit amet, cursus id lectus. Sed id ante id dui dignissim semper eu at risus. Sed eleifend placerat elementum. Etiam consequat faucibus mauris, in tristique tellus egestas ac. Nam eu odio eget lorem vulputate vulputate. Proin ut velit vitae metus sollicitudin pulvinar et at mi. Maecenas pulvinar, dui vitae pellentesque interdum, lorem enim porta ligula, in lobortis turpis justo dapibus nibh. Pellentesque ultricies tellus tellus. Aliquam erat volutpat.</p> 
    </div>
    
   	<div id="contact" class="slider content">
    	<h2>Contact Us</h2>
			<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed elit diam, suscipit in venenatis at, vestibulum et ligula. Integer molestie fermentum risus ut consequat. Fusce vulputate viverra enim vel commodo. Pellentesque pulvinar malesuada nibh at lacinia. Morbi cursus felis ut velit porta a ornare nulla aliquet. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vivamus quam dolor, mattis vel auctor ut, sollicitudin sed libero. Vivamus mollis convallis pellentesque. Quisque nunc odio, varius vulputate vestibulum sit amet, posuere vitae justo. Curabitur eu elit eu neque porttitor adipiscing sit amet in lacus. Nulla ac risus eget ligula fringilla malesuada. Phasellus ultrices luctus risus placerat vestibulum. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam pretium molestie lobortis.</p> <p>Nulla erat libero, euismod id porttitor sit amet, cursus id lectus. Sed id ante id dui dignissim semper eu at risus. Sed eleifend placerat elementum. Etiam consequat faucibus mauris, in tristique tellus egestas ac. Nam eu odio eget lorem vulputate vulputate. Proin ut velit vitae metus sollicitudin pulvinar et at mi. Maecenas pulvinar, dui vitae pellentesque interdum, lorem enim porta ligula, in lobortis turpis justo dapibus nibh. Pellentesque ultricies tellus tellus. Aliquam erat volutpat.</p>     
    </div>       
  </div>

</div>
<script type="text/javascript">
	function hidePanel(e){
		$('div.sel').animate({left: -w}, 900, function(){
			$(this).removeClass('sel').hide();
			showPanel(e);
		})
	}
	
	function showPanel(e){
		$(e).css("display", "block").animate({left: 0}, 900, function(){
			bg = e.substring(1, e.length) + '.jpg'
			$.backstretch(bg, {speed: 500});
		})
		$(e).addClass('sel');
	}
	
	var w = $('.sel').width();
	$('.slider:hidden').css({left: -w});
	$('#menu li a').click(function () {
		hidePanel($(this).attr('href'))
		return false;
	});
	$(document).ready(function(){
  var c = $('.content').width();
  $('.panelHandle').toggle(function() {
    $('.content').animate({left: '-=' + c}, 0);
  }, function() {
    $('.content').animate({left: '+=' + c}, 0);
  });
});
	
	$.backstretch("index.jpg");
</script>
</body>
</html>

Hi donboe,

Question 1:

You need to alter the parameter passed to $.backstretch()
Currently we have:

bg = e.substring(1, e.length) + '.jpg'

change this to:

bg = '/page_photos/' + e.substring(1, e.length) + '.jpg'

which will give us a string thus: “/page_photos/photo_name.jpg”, where “photo_name” is a variable derived from the <a> tag’s class.

Question2:
I have updated my demo to do what you need: http://hibbard.eu/blog/pages/sliding-panels-with-backgrounds/

Hope this helps.

WOW with capital letters. This is great. No wonder that you are member of the year!!! :tup: