1
<script>
function clear()
   {
      document.getElementById('Div1').style.display = 'block'; 
      document.getElementById('Div2').style.display = 'none';

   }
</script>

<div id="Div1">
 <p>hi</p> 
</div>
<div id="Div2">
  <p>bye</p>
</div>

<button type="button" onclick="return clear()" id="Refresh">

While clicking the refresh button, I need to show "hi", but my script function is not working. I'm trying to hide Div2 and to show Div1, but nothing happens.

James Thorpe
  • 31,411
  • 5
  • 72
  • 93
Sandhya47
  • 79
  • 7

3 Answers3

6

There's an old deprecated function, document.clear, that you appear to be clashing with. The current spec defines this as:

The clear(), captureEvents(), and releaseEvents() methods must do nothing.

If you use clear2 for instance, it works as expected.

A better, more modern approach, would be to move your script block after your HTML content, and using an event listener to hook up to the click event, that way you don't even need a function name:

<div id="Div1">
  <p>hi</p> 
</div>
<div id="Div2">
  <p>bye</p>
</div>
    
<button type="button" id="Refresh">Click</button>

<script>
    document.getElementById('Refresh').addEventListener('click', function() {
        document.getElementById('Div1').style.display = 'block'; 
        document.getElementById('Div2').style.display = 'none';
    });
</script>

In case it's not obvious, we put the script block after the HTML content so that when the script runs during page load, the getElementById('Refresh') is able to find the <button>. If the script block was at the top, when the code runs the button wouldn't exist in the page, and it would fail to find it.

James Thorpe
  • 31,411
  • 5
  • 72
  • 93
1

Ur code looks fine only change function name.. it will work for u. try any other name

like..

cleardive(), clear1()

and write ur complete button code like below

<button type="button" onclick="return clear()" id="Refresh">button name </button>

try it.

Nitesh Pawar
  • 435
  • 2
  • 11
  • `clear` is not a [reserved word](http://www.ecma-international.org/ecma-262/6.0/#sec-reserved-words), and you can use it as a function name. The problem is the scope of internal raw uncompiled handlers. – Oriol Mar 08 '16 at 13:02
  • thanku@nitesh, yes clear is default function javascript – Sandhya47 Mar 08 '16 at 13:07
0
<script>
function clearText()
   {
      document.getElementById('Div1').style.display = 'block'; 
      document.getElementById('Div2').style.display = 'none';

   }
</script>

<div id="Div1">
 <p>hi</p> 
</div>
<div id="Div2">
  <p>bye</p>
</div>

<button type="button" onclick="return clearText()" id="Refresh">
Sandhya47
  • 79
  • 7