March 19, 2012

Toggling divs in javascript

Question by Faryal Khan

I want to toggle divs by clicking on links. but things are not going well for me when I click on a link it shows a new div but don hide the previous one

JavaScript Code

<script type="text/javascript">
    function toggle(id){ 
        var el = document.getElementById(id);
        if(el != null && el.style["display"]== 'none'){ 
            el.style["display"] = "block";
        }
    }
</script>

My divs code

<?php foreach($titles_data as $title){ ?>
 <div style="display:none" id="content_<?php echo $title['idtitles'] ?>">
   <div id="left-ad"></div>
 </div>
<?php } ?>  

My links code

<?php foreach($titles_data as $title){ ?>
<li class="flag_<?php echo strtoupper($title['language']) ?>">
 <a id="title_<?php echo $title['idtitles'] ?>" href="" title="<?php echo $title['title'] ?>" onclick="toggle('content_<?php echo $title['idtitles'] ?>')">
 </a>
</li>
<?php } ?>

How can it be done so that when i click on link its respective iv becomes visible and the previous one hides?

Thanks

Answer by Starx

To toggle the display, you dont need to do that much

$("#elementid").toggle();

In reference to your question

$('a').click(function() { // however this is select all anchors, better use class
                          // selector like $(".mylinkclass")
   var id= $(this).attr('id'); //get the id
   var ids = id.splite("_"); //split the id on "_", to extract the idtitles
   $("#content_"+ids[0]).toggle(); // use that to toggle
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!