Ansh
Ansh

Reputation: 261

Hide button on completion of certain time duration

I want to hide a submit button on completion of 2 minutes of visiting that webpage. My code for this is following.

<body> is in header.php which is being called in all the pages of project,

 <body  onload="JavaScript:document.body.focus(); initSubmit();" onkeydown="return showKeyCode(event)">

I am coding the function initSubmit() in form.php as,

    <script type="text/javascript">

        function initSubmit()
        {
            document.forms[0].elements['hideit'].style.visibility = 'visible';
            setTimeout( "document.forms[0].elements['hideit'].style.visibility = 'hidden'", 120000 );
        }

</script> 

    <button type="submit" value="submit" class="btn btn-success wrp_submit_togle" id="hideit"><i class="glyphicon glyphicon-floppy-disk" ></i> Submit</button>

This is not making the button hide. Can i know where I am going wrong ?

Upvotes: 1

Views: 437

Answers (2)

Pashupati Khanal
Pashupati Khanal

Reputation: 743

The number one flaw in code is accessing element using document.forms[0]. By only allowing one of each ID on a page, getElementById can accurately retrieve it, every time, without caring about what happens to the document in the meantime.

Getting element only single time and using it by assigning as a variable is always economical if it need to be used more than once. For Quick result I decreased time for button to get visible.

Call initSubmit on window.load as follows;

function initSubmit() {
        var s = document.getElementById( 'hideit' );
                s.style.visibility = 'hidden';
                setTimeout( "document.getElementById( 'hideit' ).style.visibility = 'visible'", 5000 );
	}
    window.load = initSubmit()
<form>
  <button type="submit" value="submit" class="btn btn-success wrp_submit_togle" id="hideit">
  <i class="glyphicon glyphicon-floppy-disk" ></i> Submit</button>
</form>

Upvotes: 2

brk
brk

Reputation: 50291

Call the function initSubmit on window.load

function initSubmit() {
  document.forms[0].elements['hideit'].style.visibility = 'visible';
  setTimeout("document.forms[0].elements['hideit'].style.visibility = 'hidden'", 5000);
}


window.load = initSubmit()
<form>
  <button type="submit" value="submit" class="btn btn-success wrp_submit_togle" id="hideit">
  <i class="glyphicon glyphicon-floppy-disk" ></i> Submit</button>
</form>

Upvotes: 3

Related Questions