jwilliams17349
jwilliams17349

Reputation: 27

Hiding/Showing Elements jquery

I have been trying for several hours now trying to get my elements to hide one and show another. My script is as follows:

<script type="text/javascript">

   function () {

       $('#Instructions').hide();
       $('#GodDescription').show();
};
</script>

I don't understand why neither one is working. Default the Instructions are visible, and GodDescription is not. Right now I am just trying to get GodDescription visible and Instructions hidden when the page comes up. GodDescription in the css file has display:none;

What am I doing wrong, and what should I do?

Thank you for any help.

Upvotes: 2

Views: 115

Answers (4)

doforumda
doforumda

Reputation: 174

You could also do below using pure javascript,

<script type="text/javascript">
   window.onload = function () {
       querySelector('#Instructions').style.display='none';
       querySelector('#GodDescription').style.display='block';
   };
</script>

With jQuery you can create self invoking function too.

(function ($) {
       $('#Instructions').hide();
       $('#GodDescription').show();        
})(jQuery);

Upvotes: 0

Ryan Spice
Ryan Spice

Reputation: 23

Using vanilla javascript:

//Using Id
var element0 = document.getElementById('name');
var element1 = document.getElementById('name');
element0.style.display = 'none';
element1.style.display = 'visible';

//Using Class
var element = document.getElementsByClassName('name');
for (var i = element.length;i>=0;--i)
    element[i].style.display = 'none';

Upvotes: 0

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

If you are trying to do it as page loads you have to write this way:

$(function () {

       $('#Instructions').hide();
       $('#GodDescription').show();
});

or:

$(document).ready(function () {

           $('#Instructions').hide();
           $('#GodDescription').show();
    });

Explanation:

$(function(){ }) (shorthand for $(document).ready()) tells to execute the code inside it when the document is ready. It mean that all the HTML elements will be present and ready to be used by the JavaScript.

According to JQUERY DOCS:

A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ).load(function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready.

Upvotes: 5

faerin
faerin

Reputation: 1925

Here's a pure JavaScript solution ;)

<script type="text/javascript">
window.onload = function(){
   getDocumentById('Instructions').style.display='none';
   getDocumentById('GodDescription').style.display='block';
   };
</script>

Upvotes: 0

Related Questions