-3

I tried this code to achieve a read more effect:

    <a href="javascript:document.getElementById('morecontent1').style.display='block';">Read more</a>
    <div class="morecontent" id="morecontent1">Additional content 1</div>

but unfortunately it is not working: The complete content disappears and only the text "block" is displayed. Why? The same code in onclick is working fine.

Ulrich Bangert
  • 81
  • 1
  • 11
  • 1
    Possible duplicate of [Javascript: style.display:'block' doesn't work](http://stackoverflow.com/questions/23859408/javascript-style-displayblock-doesnt-work) – JJJ Mar 15 '16 at 17:33
  • Thanks, in the link there is the answer to my question. Obviously executing javascript in this way is not recommendable. – Ulrich Bangert Mar 18 '16 at 20:41

3 Answers3

1

Try this instead

   <script>
        function show(){
        javascript:document.getElementById('morecontent1').style.display='block';
        }
      </script>
      <body>
        <a type="button" onClick="show()">Read more</a>
        <div class="morecontent" id="morecontent1" style="display: none">Additional content 1</div>
      </body>
Alex J
  • 3,085
  • 3
  • 19
  • 29
0

You should not use inline JavaScript or inline event handlers as they create spaghetti code that is hard to debug (as you have found) and (event handlers) create global function wrappers that bind this in event handling functions to window instead of the DOM element.

The href attribute is really not the place to trigger JavaScript, the link's click event is the correct place in most cases.

This code works, however a DIV is already a block level element, so clicking your link won't actually do anything so I added an extra style in this example.

window.addEventListener("DOMContentLoaded", function(){
   var theDiv = document.getElementById("morecontent1");
   var theLink = document.getElementById("link");
   
   theLink.addEventListener("click", function(){
      theDiv.style.display = "block";
      theDiv.style.border = "1px solid red";  // Just for fun!
   });

});
   <a href="#" id="link">Read more</a>
    <div class="morecontent" id="morecontent1">Additional content 1</div>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
-1

Will not work. Use on click event to trigger a function and redirect/trigger bookmark/change things

Gary
  • 2,293
  • 2
  • 25
  • 47