Search code examples
jqueryhtmlrefer

How to refer to div by li element outside that div


on the begining I have to admit that my knowledge about programming is quite basic. I don't understand everything so maybe my question can look little lame but still my ideas run out and I need to ask.

I've used an Slide Elements tutorial and add some sliding Div in to my webside, everything works fine but in this tutorial author used a button element inside parent div and on click inner div slides. I want to use a li element from my navigation section that is outside that divs but i dont know how change the script code to keep the animation in that div. Basically it looks:

HTML:

    <ul id="navigation">
 <li class="about"><a title="A" href="#" > </a></li>
 <li class="search"><a title="P" href="#" ></a></li>
 <li class="photos"><a title="G" href="#" ></a></li>
 <li class="rssfeed"><a title="U" href="#" ></a></li>
 <li class="contact"><a title="K" href="#" ></a></li>
</ul>

    <div id="IDcontent" class="slide" >
<button>slide it</button>
<div class="inner"  style="margin-left: 100%"> test </div>
</div>      

I manage to change script code that an li element triggers a click action not the button, but after click, it not slide the div but it slides a next li element.

SCRIPT CODE:

<script>

$(document).ready(function() {
  $('#navigation li').click(function() {
    var $marginLefty = $(this).next();
    $marginLefty.animate({
      marginLeft: parseInt($marginLefty.css('marginLeft'),10) == 0 ?
        $marginLefty.outerWidth() :
        0
    });
  });
});

  </script>

Any sugestions ?

Big Thanks!


Solution

  • Because of this line of code,

    var $marginLefty = $(this).next();
    

    the next li element after what was clicked on is animated since you later do $marginLefty.animate(). If you want to animate the div, you should set marginLefty to the div element. So replace that line with:

    var $marginLefty = $('.inner');
    

    To find out which li was clicked, you can do

    // $(this) refers to the element that was clicked
    $liClass = $(this).attr("class") 
    

    inside the click handler. Then you can change the content of the div based which li was clicked, and by using the html() function. For example,

    var content;
    if($liClass == 'about'){
     content = 'about clicked';
    }
    else if($liClass == 'search'){
        content = 'search clicked';
    }
    //more code here
    //more code here
    $marginLefty.html(content);
    

    You can find more information about .attr() and .html() over here: http://api.jquery.com/attr/ and http://api.jquery.com/html/