arunpandiyarajhen
arunpandiyarajhen

Reputation: 653

How to change the visibility of a <div> tag using javascript in the same page?

I'm working on a simple javascript code.

Based on the condition I should change the visibility of the tag from hidden to visible.

I should use javascript alone. No jQuery or AJAX. Any idea or suggestion please.

Upvotes: 9

Views: 98225

Answers (6)

One way to do this would be to create the control logic in JavaScript and add it in the "script" tag of the document. Then apply the logic to hide/show the "div" element.

I created an example HTML document based on “A First HTML Document” on page 16 (Musciano and Kennedy, 2002). It includes a "div" tag within the "body" tag near the top. The ShowAndHide function has been included in the "script" tag within the "head" tag. An application of the ShowAndHide may be found in the other "script" tag within the "body" tag near the end.

You can find the HTML example as an attachment to the PDF document "Show-and-Hide Control Logic: Inspired by a Question at Stack Overflow".

Reference

Musciano, C. and Kennedy, B. (2002). HTML and XHTML: The Definitive Guide, Fifth Edition. Sebastopol, CA: O’Reilly Media Inc.

Upvotes: 0

uutsav
uutsav

Reputation: 409

Though asked not to be done with jquery, but can be done as: $('.my_div_tag_id').css('visibility','hidden');

Upvotes: 2

mornaner
mornaner

Reputation: 2424

Using the visibility attribute:

Show the div with id="yourID":

document.getElementById("yourID").style.visibility = "visible";

To hide it:

document.getElementById("main").style.visibility = "hidden";

Using the display attribute:

Show:

document.getElementById("yourID").style.display= "block";

Hide:

document.getElementById("yourID").style.display= "none";

Upvotes: 34

2plus
2plus

Reputation: 261

Call this function when you want to show the div. Write that conditions in your segment/case.

function showDiv() {
    document.getElementById('divId').style.display = 'block';   //  or 'inline'
}

Let me know your feedback.

Upvotes: 1

Hitesh Bavaliya
Hitesh Bavaliya

Reputation: 941

<div id="contentDiv">
    This is the content .
</div>

if you want to change the visibility of div with id="contentDiv" using javascript then you can do with..

var eleDiv = document.getElementById("contentDiv");


    // based on condition you can change visibility
if(eleDiv.style.display == "block") {
        eleDiv.style.display = "none";
}
else {
    eleDiv .style.display = "block";
}

Hope this code helps you........

Upvotes: 4

Anton Baksheiev
Anton Baksheiev

Reputation: 2251

Visible:

var elem = document.getElementById("IdOfEl");
elem.style.display="block";

Hide:

var elem = document.getElementById("IdOfEl");
elem.style.display="none";

Upvotes: 1

Related Questions