I have a list that contains input fields along with delete link elements. I want to display the delete link element when the user hovers over the respective input field. Additionally, clicking on the close button (X) should hide the entire list item (li) from the list.
Currently, I am using vanilla JavaScript to achieve this functionality, but I have encountered an issue. The code I have written only shows the first close button, regardless of which field I hover over.
Custom HTML
<ul class="social-links-list">
<li class="social-link">
<input type="text" name="" id="" placeholder="http://facebook.com/id">
<span class="delete-link" onclick=''>X</span>
</li>
<li class="social-link">
<input type="text" name="" id="" placeholder="http://facebook.com/id">
<span class="delete-link">X</span>
</li>
<li class="social-link">
<input type="text" name="" id="" placeholder="http://facebook.com/id">
<span class="delete-link">X</span>
</li>
</ul>
Styling with CSS
ul {
list-style: none;
}
input[type='text'] {
height: 1rem;
padding: 0.5rem;
margin-bottom: 1rem;
border-radius: 3px;
border: 1px solid #ccc;
}
.delete-link {
color: red;
opacity: 0;
cursor: pointer;
}
JavaScript Approach
var socialField = document.querySelectorAll('.social-link');
socialField.forEach(function(el) {
el.addEventListener('mouseover', function(){
closeBtn.style.opacity = 1;
});
el.addEventListener('mouseout', function(){
closeBtn.style.opacity = 0;
});
var closeBtn = document.querySelector('.social-link .delete-link');
for (i = 0; i < closeBtn.length; i++) {
closeBtn[i].addEventListener("click", function() {
this.parentElement.style.display = 'none';
});
}
});
For a live example, you can check this JSFiddle.