-3

I have a page in which there is an anchor tag: <a href="tut.html#div2">jump to div2</a>.

This anchor tag opens tut.html, which has a div with id=div2:

<div class="container">
    <div class="row">
        <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
            <div id="div1">
                --some content--
            </div>
            <div id="div2" style="display:none;">
                --some content--
            </div>
        </div>
    </div>
 </div>

By default, the contents of div2 are hidden. How can I display or fade in its contents when a user clicks on a hyperlink in another page?

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Vivek Singh
  • 61
  • 1
  • 8

3 Answers3

1

You can easily check the hash that is passed in and use that to display the appropriate block:

window.onload = function(){
    var element = document.querySelector(location.hash);
    if(element) element.style.display = "block";
}
somethinghere
  • 16,311
  • 2
  • 28
  • 42
1

your href link should not link to the page, just to the anchor :

<a class="myButton" href="#div2">link</a>
<div class="container">
   <div class="row">
      <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
           <div id="div1">
              --some content--
           </div>
           <div id="div2" style="display:none;">
              --some content--
           </div>
      </div>
  </div>
</div>

Using jQuery, you should have a function in the bottom of your document which would handle your click like this :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">   </script>
<script>
    $(function () {
        $('a.myButton').on('click', function(event){
          event.preventDefault();
          $('div2').fadeIn('slow');
          return false;
        })
    });
</script>
  • But this will work only if i have the anchor tag in the same page.In this case,anchor tag lies on different page. – Vivek Singh Jul 09 '15 at 17:52
  • Ok then if your link is on a different page, then keep your href like you said: jump to div2 and on the page tut.html add this script : $(function () { var hash = window.location.hash; if(hash == '#div2') $(hash).fadeIn('slow'); }); – Jerome Poslednik Jul 15 '15 at 12:44
1

If the link goes to a new page:

<a href="tut.html#div2">link</a>

On the bottom of the new page 'tut.html' :

<script>
  $(function () {
    var hash = window.location.hash;
    if(hash == '#div2') $(hash).fadeIn('slow');
  });
</script>