Search code examples
javascriptmedia-queriesvisibilitymouseout

how to disable mouseout visibility="hidden" effect for medias smaller than 768px?


I am pretty new at Javascript. I created this effect where text appears under an image icon when the user hovers over it. I would like the effect to only work when the screen is over 768px and for the text to just stay visible at all times when viewed on smaller devices. I've tried using different variants of

 if (screen.width < 768px) {}  
 and  
 @media all and (min-width: 768px) {} else {}  

to control the effect to my liking but without any luck. Help??? Here is my code:

<section id="s1">
<h1><a href="web/services.html">
     <img src="images/ICON-TRANSCRIPTION.png" class="hover"></a></h1>
<p class="text">TRANSCRIPTION</p>
</section>

<script> 
$('.hover').mouseover(function() {
$('.text').css("visibility","visible");
}); 

$('.hover').mouseout(function() {
$('.text').css("visibility","hidden");}); 

</script>

Solution

  • If you must do it via JS(this can be accomplished with CSS media queries), first you should get the width of the window and set it as a variable, then you can set up your conditional statement like so:

    function mouseVisibility() {
        var w = $(window).width();
        if (w > 767) {
            $('.hover').mouseover(function() {
                $('.text').css("visibility","visible");
            }); 
    
            $('.hover').mouseout(function() {
            $('.text').css("visibility","hidden");}); 
        }
    }
    mouseVisibility();
    

    Additionally, you should fire the function again if the user resizes the browser window:

    $(window).resize(function() {
        mouseVisibility();
    });