user3553869
user3553869

Reputation: 59

CSS :hover on mobile act as click

I currently have a div with some information in it. See the example below:

<div class="verstuurd" onclick="alert('clicked!');">
    <div class="titel"><span>Title</span><img src="imageurl"/></div>
    <div class="image"><img src="imageurl"/></div>
    <div class="tekst"><p>some text</p></div>
    <div class="hover">
        VISIBLE TEXT
    </div>
    <div class="delen">
        VISIBLE AFTER HOVER
    </div>
</div>
</div>

The :hover function works perfectly and the "delen" part is shown and the "hover" part is hidden. I only got a problem on mobile devices. If I scroll down the page on a mobile device and I touch the div, the hover will be triggered.

The answer I am looking for is; how am I able to use :hover on PC's and some sort of click event on mobile devices? So that I have to click in order to change the content and a second click will trigger the onclick of the div.

As an example of my inspiration see the website.

If you hover an item it will show the heart icons. PC uses this with hover and mobile needs a click to be shown. Unfortunately I can't find the source code which triggers this.

Upvotes: 1

Views: 2968

Answers (1)

Coty Embry
Coty Embry

Reputation: 978

Are you talking about, you want an onClick="theFunctionNameToBeCalled()" fired when a div is touched (specifically on a mobile device?)

if you want that, you can use

$( "#divIdToBeTouced" ).click(function() {
  //do something with a function here
});

or you could use plain ol' JavaScript to do the task.


<!DOCTYPE html>
<html>
<head>
<title>Coty's Title</title>
</head>
<body>

<div id="divIdToBeTouched" onmouseover="theFunctionToBeCalled()" onClick="theFunctionToBeCalled()">
I'm a div
</div>

<script>
var i = 0;
function theFunctionToBeCalled(){
  i++;
  if(i == 2) {
    //do what you wanted once the onClick event was fired
    alert("i == 2");
    //now make sure to reset the flag that was made so it will work     next time
    i = 0;
  }
  else {
    //change the content
    alert("i == 1");
  }
    //do something interesting here if you want to
}

</script>
</body>
</html>

paste that code on this page http://www.w3schools.com/html/tryit.asp?filename=tryhtml_default? and you can try it out on a browser computer and try it on a mobile device and it should work I tested it

Now make the hover event also call this function and it'll cover both evens


Extra info:

I've heard arguments with two possible paths to go from here and some say one way is "dangerous", I'll list the sides below If you wanted to know...

cont'd

the other argument is there needs to be an event listener added instead of a direct function call This seems more safe. I think because it can help hide the function call its self..? I'm not sure.

Hope this helps

Upvotes: 1

Related Questions