Reputation: 733
I maybe losing my marbles here, but I feel like this is pretty straightforward JavaScript. For some reason, the 1st addEventListener call on the #recipes element is firing the statements in both the 1st and 2nd event handlers, and the 2nd event handler isn't working at all.
var recipes = document.getElementById('recipes');
var close_heart = document.getElementById('close_heart');
var recipes_container = document.getElementById('recipes_container');
recipes.addEventListener('click', function(){
recipes_container.style.display = 'block';
});
close_heart.addEventListener('click', function(){
recipes_container.style.display = 'none';
});
<div id="recipes"><a href="#" id="close_heart"><span>Recipes</span></a></div>
<section id="recipes_container"><a href="#" class="fa fa-gittip"></a>
<h1>Real Mac & Cheese</h1>
<ul>
<li>Rule #1 – Use only real cheese (no powdered cheese ever!)</li>
<li>Rule #2 – Use multiple cheese-type varieties (ex: sharp cheddar, monterey jack, bleu)</li>
<li>Rule #3 – Choose an extra protein like bacon to liven it up!</li>
</ul>
</section>
</div>
Thank you.
Upvotes: 1
Views: 98
Reputation: 17651
Without your HTML I can only speculate, but I'd be willing to bet that what you're encountering is event bubbling.
#recipes
likely encapsulates #close_heart
such that a click
on #close_heart
will bubble up and trigger the click
event handler for #recipes
as well.
You can use .stopPropagation() to resolve this issue. It will prevent the event from bubbling up the DOM and triggering click
event handlers on parent elements.
recipes.addEventListener('click', function(event){
event.stopPropagation();
recipes_container.style.display = 'block';
});
close_heart.addEventListener('click', function(event){
event.stopPropagation();
recipes_container.style.display = 'none';
});
Here's another StackOverflow question with a helpful explanation of event capturing and event bubbling: What is event bubbling and capturing?
Edit: Now that you've included your HTML, I can see that is indeed an issue.
Upvotes: 2
Reputation: 41
Perhaps you are missing to assign a proper id to the elements. Check the following code, it should work for your case too:
<html>
<head>
<title> The Title </title>
</head>
<body>
<button id="recipes"> Recipes </button>
<button id="close_heart"> Close_heart </button>
<h1 id="recipes_container"> Recipes Container </h1>
<script>
var recipes = document.getElementById('recipes');
var close_heart = document.getElementById('close_heart');
var recipes_container =
document.getElementById('recipes_container');
recipes.addEventListener('click', function(){
recipes_container.style.color = "blue";
});
close_heart.addEventListener('click', function(){
recipes_container.style.color = "orange";
});
</script>
</body>
</html>
Upvotes: 0
Reputation: 733
I simply misplaced an id attribute. The close_heart id should have been placed within the anchor element nested in the section.
Upvotes: 0