user2111911 user2111911 - 5 months ago 7
Ajax Question

jquery code not working on window ready. Also i want to create a button to close the enlarge div

I am working on an web app, with 4 boxes on each page, pages are loading from external html example file code.

$(document).ready(function(){
// Load Home Content
$('#content').load('pages/sample.html');

//Load Content Using Menu Links
$('.main-menu a').click(function(){
var page = $(this).attr('href');
$('#content').load('pages/' + page + '.html');
return false;
});
});


Now i have made 4 divs of equal size and height. On click of any div it enlarges and attain the height and width of the parent.
Using the code. The clicked div will be enlarged and other divs will be hidden.

$(window).load(function(){
$(".box").click( function() {
var width = $('.boxes').innerWidth() + 'px',
height = $('.boxes').innerHeight() + 'px';
console.log(width);
console.log(height);
$(this).animate(
{
"height": height,
"width": width
},500);

$(this).find(".box-container").hide();
$(this).find(".box-content").show();

$(".box").not(this).hide();



});

});


But there are some problems.


  1. The div enlarge code is not working on ready function, it works only one time and then it stop working.

  2. Secondly i need help in creating a close button so i can reverse the above function.

  3. Last is there way that i can navigate between these divs without closing from one enlarge div to another enlarge div content.


Answer

Heres what i would do:

$(document).ready(function(){
     var $currentBox = false;
     var open = false;//this will help close the large div view
     var origHeight = $('.box').innerHeight() + 'px';
     var origWidth = $('.box').innerWidth() + 'px';

     $(".box").click( function() {
        if(open){
           $currentBox = false;
           $(this).animate({
               "height": origHeight,
               "width": origWidth
           },500);
           $(".box").show();
           $(".box-container").show();
           open = false;
        }else{
           $currentBox = $(this);
           var width = $('.boxes').innerWidth() + 'px',
           height = $('.boxes').innerHeight() + 'px';
           $(this).animate({
             "height": height,
             "width": width
           },500);

           $(this).find(".box-container").hide();
           $(this).find(".box-content").show();

           $(".box").not(this).hide();
           open=true;
        }
     });  
     //listen to left and right key events
     window.addEventListener( 'keydown', function( e ) { 
        if($currentBox!=false){//if full box view     
           if (e.keyCode == '39') {//key left
              //code to show prev box  
               e.preventDefault();
           }else if (e.keyCode == '37') {//key right
              //code to show next box  
              e.preventDefault(); 
           } 
        }
     });
 });
Comments