...

View Full Version : Hiding HTML element (node) - improvement is needed



ozvena
05-08-2004, 05:20 AM
Hi,

I need to hide a paragraph when user clicks on a different paragraph. The code below works but seems to be little bit too complicated. Is there a more elegant way? Thank you!

-----------------------------------------------------------------
function hide(elementId)
{
var ourEle = document.getElementById(elementId);
var parent = ourEle.parentNode;

var blankEleP = document.createElement("p");
var blankText = document.createTextNode("");
blankEleP.appendChild(blankText);

parent.replaceChild(blankEleP, ourEle);
}

<p onclick ="hide('hobbies');">HOBBIES</p>
<p id="hobbies"> TEST TEST TEST</p>

-----------------------------------------------------------------
I used replaceChild instead of removeChild because eventually I want to do a toggle function. May be that is not a good enough reason. Well, what do you think?

ozvena
05-08-2004, 06:08 AM
I modified it to implement a toggle function. It hides the element but it does not recreate the element on a second click. How to make it to work?

--------------------------------------
var bHobbies = true;
var nodeHobbies;
var parentHobbies;

function init()
{
nodeHobbies = document.getElementById("hobbies");
parentHobbies = nodeHobbies.parentNode;
}

function toggle()
{
var blankEleP = document.createElement("p");
var blankText = document.createTextNode("");
blankEleP.appendChild(blankText);
blankEleP.setAttribute( "id", "hobbies" );

if(bHobbies)
{
bHobbies = false;
parentHobbies.replaceChild(blankEleP, nodeHobbies);
}
else
{
bHobbies = true;
parentHobbies.replaceChild(nodeHobbies, blankEleP);
}
}
// end script -->
</script>

--------------------------------------
<p onclick="toggle();">HOBBIES</p>

<p id="hobbies">test</p>

<script>
init();
</script>

--------------------------------------

swmr
05-08-2004, 08:48 AM
Well, I don't know if this is at all less complicated (or an improvement), but since Moz returns a textnode for "nextSibling", this is all I could think of, for now...



<html>
<body>
<script type="text/JavaScript">
function f(el){
var tgN = document.getElementsByTagName(el.tagName);
for(var i = 0; i < tgN.length; i++){
if(tgN[i] == el){
var nextEl = tgN[i + 1];
break;}
}
if(nextEl){
var elStyle = nextEl.style;
elStyle.display != "none" ? elStyle.display = "none" : elStyle.display = "block";}
}
</script>

<p onclick="f(this)">testFunction</p>
<p>test</p>
</body>
</html>

ozvena
05-08-2004, 04:15 PM
I really appreciate it!!!! It not only works (unlike my code) but it is more elegant too! :thumbsup:



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum