WordPress站点hover触发元素隐藏的JS脚本无生效问题
Hey there! It’s super frustrating when code works smoothly in a test environment like JSFiddle but falls flat on your live site. Let’s break down the most likely reasons and fixes for your hover event problem:
1. DOM isn’t fully loaded when your code runs
JSFiddle often wraps your code in a DOM-ready handler by default, but your site might be executing the jQuery code before elements like #maps1, #maps2 finish rendering. Even though you’re using a self-executing function, that doesn’t automatically wait for the DOM to be ready.
Fix: Wrap your code in a DOM-ready handler to ensure target elements exist before binding events:
jQuery(document).ready(function($) { $("#maps1").hover(function(){$("#kontakt_os_1").hide();}); $("#maps2").hover(function(){$("#kontakt_os_2").hide();}); $("#maps3").hover(function(){$("#kontakt_os_3").hide();}); });
Alternatively, move your <script> tag containing this code to right before the closing </body> tag—this guarantees all page elements are loaded first.
2. Target elements are dynamically generated
If your map elements (#maps1, etc.) are added to the page after the initial load (e.g., loaded via a map plugin or AJAX), your static hover() binding won’t work because the elements didn’t exist when the code ran.
Fix: Use event delegation to attach the hover event to a parent element (or document) that exists on page load:
jQuery(document).ready(function($) { $(document).on('mouseenter mouseleave', '#maps1', function() { $("#kontakt_os_1").hide(); }); $(document).on('mouseenter mouseleave', '#maps2', function() { $("#kontakt_os_2").hide(); }); $(document).on('mouseenter mouseleave', '#maps3', function() { $("#kontakt_os_3").hide(); }); });
Note: hover() is a shortcut for mouseenter and mouseleave, so we explicitly bind both events with delegation to replicate the same behavior.
3. jQuery conflicts or missing library
Double-check if jQuery is properly set up on your site:
- Open your browser’s developer tools (F12) and check the Console tab for errors like
$ is not definedorjQuery is not defined. - Make sure your jQuery script tag loads before your custom hover code.
- If there’s a conflict with other libraries, your self-executing function should already handle
$safely, but you can test replacing$withjQueryto rule out issues.
4. CSS is blocking hover events
Sometimes an invisible overlay element sits on top of your map elements, preventing the hover event from reaching them. Or the pointer-events CSS property might be set to none on the map elements, which disables all mouse interactions.
Fix:
- Use your browser’s developer tools to inspect
#maps1—check if another element is covering it (look at the box model in the Elements tab). - Verify the CSS for your map elements doesn’t include
pointer-events: none;—if it does, change it topointer-events: auto;.
内容的提问来源于stack exchange,提问作者Paweł Skaba

