Hover event, but not on touch/mobile devices

Discussion in 'Programming' started by 7643sfsag6, Nov 25, 2019.

  1. #1
    Hi All,
    I am trying to create a hover event that shows an image. On my desktop/laptop it fires correctly. However on a mobile (touch), the image only appears when the modal link is clicked, then it is sticky (it stays on screen).
    On mobile or touch-screens, i don't want the hover event to fire.
    Here is what i am working with.

    Jsfiddle
    https://jsfiddle.net/postcolonialboy/pxwd34ka/4/

    HTML
    <a href="#test" id="test-parent">Hover to show image</a>
    <img class="preview" id="test-child" src="https://mayvers.com.au/wp-content/uploads/2017/09/test-image.jpg" />
    <script>
      $("#test-parent").hover(function() {
        $("#test-child").fadeToggle();
      });
    </script>
    HTML:
    CSS
    .preview {
      display: none;
      position: absolute;
      bottom: 0;
      right: 0;
      z-index: 1;
      height: 50%;
    }
    Code (CSS):
     
    Last edited: Nov 25, 2019
    7643sfsag6, Nov 25, 2019 IP
  2. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #2
    A good start would be to not use JavaScript -- much less the mind-numbing derpitude that is jQuery -- to do CSS' job.

    Step 1, gut out all the garbage the markup doesn't need.

    
    <a href="#test" class="hoverNext">Hover to show image</a>
    <img
    	src="/wp-content/uploads/2017/09/test-image.jpg"
    	alt="describe this, alt is not optional!"
    >
    
    Code (markup):
    Step 2, let CSS do the heavy lifting.

    
    .hoverNext + img {
    	position:absolute;
    	bottom: 0;
    	right:100vw;
    	height:50%;
    	z-index:1;
    	opacity:0;
    	transition:right 0s 0.5s, opacity 0.5s;
    }
    
    .hoverNext:hover + img {
    	right:0;
    	opacity:1;
    	transition:right 0s, opacity 0.5s;
    }
    
    Code (markup):
    Since mobile has NO hover states, it won't do anything. Note, I'm not sure that should be an Anchor, but I left that alone for now.

    This hasn't been JavaScript's job since we stopped caring about IE7/earlier.

    The mere presence of "fadeToggle" in jQuery's mental huffing midgetry is just the pigeon poop on the monument to ignorance, incompetence, and ineptitude that are front-end frameworks.
     
    deathshadow, Nov 25, 2019 IP
  3. 7643sfsag6

    7643sfsag6 Member

    Messages:
    58
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    43
    #3
    great thanks @deathshadow
    in this case a full css solution works like a dream!
     
    7643sfsag6, Nov 25, 2019 IP