3

JavaScript:

function hide_article() {
    var htmlElement = document.getElementsByTagName("article")[0];
    htmlElement.setAttribute("visibility", "hidden");
    console.log("hiding");
};

HTML:

<div id="right-hand-side">
   <img src="resources/Logo.png" onmouseover="hide_article()" onclick="hide_article()"/>
</div>

This function is being called but the article is not being hidden. Any idea why? Cheers.

0

2 Answers 2

7

Yes - visibility is a CSS rule name, not an HTML attribute.

htmlElement.style.visibility = 'hidden';

Bear in mind, though, that, unless you have good reason to use visibility (and there are some), you'd normally hide elements via display (= 'none') rather than via visibility.

Also, you're assuming that your function will find an element. If it doesn't, your code will error. Best to check this first:

function hide_article() {
    var htmlElements = document.getElementsByTagName("article");
    if (htmlElements.length) { //<-- check before continuing
        htmlElements[0].style.visibility = "hidden";
        console.log("hid element");
    }
};
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks I will add in that check. Can I do a check to see if it is hidden and change it to visible? I tried this: function hide_article() { var htmlElement = document.getElementsByTagName("article")[0]; if (htmlElement.getAttribute('visibility') === 'visible'){ htmlElement.style.visibility = 'hidden'; console.log("hiding") } else { htmlElement.style.visibility = 'visible'; console.log("showing") } };
@user3164083 or in short: htmlElement.style.visibility = htmlElement.getAttribute('visibility') === 'visible' ? 'hidden' : 'visible';
Once again, you're treating visibility as though it were an attribute. It's not: it's a sub property of the style property. So: htmlElements[0].style.visibility = htmlElements[0].style.visibility == 'hidden' ? 'visible' : 'hidden';
2

This is the statement that you want:

htmlElement.style.visibility = 'hidden';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.