JS help...

by 4 replies
5
Hi All,

I'm developing a new site.

I want to show somthing on click, eg: READ MORE, will drop down the text.

heres my code so far:

Code:
<div id="HiddenDiv" style="display:none;">Content</div>

<a href="javascript:ShowDiv()">Show Div</a>

<script language="javascript">
     function ShowDiv()
        {
           document.getElementById("HiddenDiv").style.display = '';
        }
</script>
This code works great.. does the job nice and easy, however I want to use this code multiple times on the page, and its not allowing it. I can only use it 1 time per page.. Can anyone tell me a way to make it work more than once?

I have put the js into the header, an it still don't work..

Cheers.
#programming
  • Your selector is an ID, you should have only one ID per page so that is why it is selecting only the first one. Depending on how your function works you have two options:

    1. Change the selector from an ID to a class
    2. Change the subsequent ID's (ie: HiddenDiv_2, HiddenDiv_3, etc) and the functions (ShowDiv_2, ShowDiv_3)
    • [ 1 ] Thanks
  • Thanks Andrew.

    I can only add it 1 time as its a post template, but ill use it with php to create a new div name each time

    thanks, it solved my issue.
    • [1] reply
    • Use jQuery! It is overkill for this particular task alone, but you will have many other uses for JS across your application. Don't fight the tide, and use a mature library.

      In jQuery, you can structure as so:

      Code:
      <a href="javascript:;" class="show-more">Show Div</a>
      <p class="more">More text here, hidden by default</p>
      
      <script>
        $('.show-more').click(function(){
            $(this).closest('.more').show();
        });
      </script>
      That is very rough and purposely so to give you a general idea.
  • You could also use CSS, a <span> inside the a tag (you don't even need an a tag at all, could be a simple div, too)... no JS needed.

    Code:
    <div>Show More<span>More Text</span></div>
    Code:
    div span{display:none;}
    div:hover span {display:block;}
    This is just an example but does what you need.

Next Topics on Trending Feed