I have some divs and if i hover them I want an popup to show. I have six divs and six popups to show but not all at once instead only one per one.
The first function works fine but then the other do not work how can I move them all to one snippet?
<script>
document.addEventListener('DOMContentLoaded', function() {
let elements = document.querySelectorAll('#Mitarbeiter1Punkt');
let popupposts = ['647'];
elements.forEach(function(e, i) {
e.addEventListener('mouseenter', function() {
elementorProFrontend.modules.popup.showPopup({
id: popupposts[i]
});
});
e.addEventListener('mouseleave', function(event) {
jQuery('body').click();
});
});
});
document.addEventListener('DOMContentLoaded', function() {
let elements = document.querySelectorAll('#Mitarbeiter2Punkt');
let popupposts = ['656'];
elements.forEach(function(e, i) {
e.addEventListener('mouseenter', function() {
elementorProFrontend.modules.popup.showPopup({
id: popupposts[i]
});
});
e.addEventListener('mouseleave', function(event) {
jQuery('body').click();
});
});
});
</script>
CodePudding user response:
I would use an array of objects that maps the div IDs to the popup IDs. Loop over the array and set up all the event listeners.
document.addEventListener('DOMContentLoaded', function() {
let popupMap = [{
div: '#Mitarbeiter1Punkt',
popup: 647
},
{
div: '#Mitarbeiter2Punkt',
popup: 646
}
];
popupMap.forEach(({div, popup}) => {
let e = document.querySelector(div);
e.addEventListener('mouseenter', () => elementorProFrontend.modules.popup.showPopup(popup));
e.addEventListener('mouseleave' () => jQuery('body').click());
});
});
CodePudding user response:
An alternative option would be to make this data-driven rather code-driven - ie the data is in the HTML, not the js. And as you're using jquery already, make use of jquery.
It's unlikely this will fix the root-cause of your issue as that's not been established (still waiting for complete sample) - this is to show how to combine this into a single function that doesn't need to be changed as you add new HTML.
$(".punkt").on("mouseenter", function() {
var id = $(this).data("popup-id");
$(".popup[data-popup-id='" id "']").show();
});
$(".punkt").on("mouseleave", function() {
var id = $(this).data("popup-id");
$(".popup[data-popup-id='" id "']").hide();
});
div {
border: 1px solid rebeccapurple;
width: 50px;
height: 50px;
text-align: center;
}
.popup {
display: none;
}
<div class='punkt' data-popup-id='A'>
1
</div>
<div class='punkt' data-popup-id='B'>
2
</div>
<div class='popup' data-popup-id='A'>
A
</div>
<div class='popup' data-popup-id='B'>
B
</div>