I'm creating a site that has a status bar that updates its innerHTML depending on what is mouseovered by the user. The function that does this has a bunch of if statements in it but if the if statement finds that the conditions don't exist it throws alot of errors. For example: I have an if statement that checks what the id is of the element 3 parent elements above a child element like this: if( element.parentElement.parentElement.parentElement.id == 'body' ). But because i'm using one function this if statement throws the error 'Uncaught TypeError: Cannot read property 'parentElement' of null' when the element doesnt meet that condition. My question: Is there a way to first check if the if statement is even going to work before i use it? This might sound dumb but It seems thats the only way to avoid the errors unless I use multiple functions - which I don't want. My code is below and heres a JS BIN of a very simplified version of my program: http://ift.tt/14wrR1J ( open the console to see my errors ).
<html>
<body>
<header id = "header" onmouseover = "statusSet( this )">
<p>Header</p>
</header>
<section id = "body">
<div id = "area1">
<div>
<p id = "p1" onmouseover = "statusSet( this )">
paragraph
</p>
<p id = "p2" onmouseover = "statusSet( this )">
paragraph
</p>
<p id = "p3" onmouseover = "statusSet( this )">
paragraph
</p>
</div>
</div>
</section>
<footer><p id = "statusBar">Status Bar</p></footer>
<script>
document.body.addEventListener( 'mouseover', function( element ){
statusSet( element.target );
});
function statusSet( element ){
var elementId = element.id;
var elementInner = element.innerHTML;
if( elementId == 'body' || elementId == 'statusBar' ){
document.getElementById( 'statusBar' )
.innerHTML = 'hovering over body';
}
else if( element.parentElement.parentElement
.parentElement.id == 'body' ){
document.getElementById( 'statusBar' )
.innerHTML = 'hovering over paragraphs';
}
else if( element.id == 'header' ){
document.getElementById( 'statusBar' )
.innerHTML = 'hovering over header';
}
}
</script>
</body>
</html>
Aucun commentaire:
Enregistrer un commentaire