Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Jannik Spiessens
13,229 Pointsif statement not working
I wonder why the console doesn't print out "lol"?
The HTML:
<div id="nav">
<ul>
<a href=""><li>Jannik</li></a>
<a href=""><li>Alex</li></a>
</ul>
</div>
The javascript:
$("#nav a").each(function(){
$(this).click(function(event){
event.preventDefault();
var val = (this).innerText;
console.log(val);
$content.children().fadeOut(400, function(){
$content.html("");
});
var HTML = "<ul>";
console.log(val);
if (val === "Jannik") {
console.log("lol");
}
});
});
2 Answers
Sean T. Unwin
28,690 PointsRemove the brackets around this in the variable val declaration.
Also, if you're using Firefox, it doesn't recognize innerText so you have to use textContent.
So the val declaration should look like:
// val equals this.innerText (if used) or this.textContent (if used instead)
var val = this.innerText || this.textContent;
You are also going to have to remove, move below the if statement, comment out, or change (see below) the following:
$content.children().fadeOut(400, function(){
$content.html("");
});
$content doesn't exist and if you are using it as a jQuery variable you have put brackets around it, i.e. $(content).
However, if you are trying to fade out the content of #nav then you can have the statement look like this:
$(this).parent().children().fadeOut(400);
Furthermore, you should try, when possible, to declare variables at the beginning of the function.
So for this to work as you intended you would have:
$("#nav a").each(function(){
$(this).click(function(event) {
event.preventDefault();
var val = this.innerText || this.textContent;
var HTML = "<ul>"; // you don't really need this
$(this).parent().children().fadeOut(400);
console.log( val);
if (val == "Jannik") {
console.log("lol");
}
});
});
shezazr
8,275 PointsOk after doing some debugging, I have realised that when I do length of val it comes to 7 for Jannik when it should be 6, also outputting this value to html results in:
"Jannik "
There is a carriage return or a space.
Jannik Spiessens
13,229 PointsJannik Spiessens
13,229 PointsThanks for answering that good and quickly!
(The $content var was declared somewhere else and i needed the HTML var further in the code)
Sean T. Unwin
28,690 PointsSean T. Unwin
28,690 PointsGotchya. Glad I could help. :)