I am looking for some help using JS or jQuery to show and hide a div. I have social media share in WordPress loop. I understand how to make show and hide div on click. But in WordPress loop, when I click share button all divs appear.
jQuery(document).ready(function() {
$('.loop-item .share-btn').click(function(){
$('.loop-item .share-icon').toggle();
});
});
body {
font-family: Arial;
font-size: 16px;
}
.loop-container {
display: flex;
}
.loop-item {
width: 200px;
margin: 10px;
padding: 15px;
border: 1px solid #dedede;
}
.loop-item h4 {
margin-top: 0;
}
.social-share-box {
font-size: 14px;
}
.social-share-box .share-btn {
cursor: pointer;
margin-bottom: 8px;
}
.social-share-box .share-icon {
display: none;
}
.social-share-box .share-icon.active {
display: block;
}
.social-share-box .share-icon a {
font-size: 12px;
width: 14px;
height: 14px;
border: 1px solid #dedede;
border-radius: 90px;
display: inline-block;
text-align: center;
padding: 2px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="loop-container">
<div class="loop-item">
<h4>Item Title Loop 1</h4>
<div class="social-share-box">
<div class="share-btn">
Click here share:
</div>
<div class="share-icon">
<a>F</a>
<a>T</a>
<a>P</a>
</div>
</div>
</div>
<div class="loop-item">
<h4>Item Title Loop 2</h4>
<div class="social-share-box">
<div class="share-btn">
Click here share:
</div>
<div class="share-icon">
<a>F</a>
<a>T</a>
<a>P</a>
</div>
</div>
</div>
</div>
As in my code, if I click "Click here share:" the social icon will appear in all posts.
My questions:
- How can I make the social icon only appear on the post I clicked?
- How to hide the active social media icon when I click on another "Click here share:"?
- How to hide the active social media icon if I click outside?
2
Answers
Currently, whenever you press a button, you event handler toggles every .share-icon div.
What you want to do is toggle only the one that is a sibling of the clicked button. Also, you want to hide all the other ones.
To do so, use $(this) to refer to the clicked button
(NB : answers to the thers questions are also in the following code)
event.target.closest(selector) gets the closest element targeted by your click that matches your selector
Check if the current icons are
:visible