leclerk leclerk - 2 months ago 21
CSS Question

jquery append class with hover AND touch for mobile device

I'm using the script below to add a class 'hover' to a div with the class 'reveal-area'.

jQuery(document).ready(function(){
$(".reveal-area").hover(
function () {
$(this).addClass("reveal-show");
},
function () {
$(this).removeClass("reveal-show");
}
);
});


This works fine on PC - but how can I add a function to include a touch activation (to append the class) on a mobile device? thanks

Answer

I think you need something like this

(function ($) {
	'use strict';
    $(document).ready(function() {

		//check device type
		function deviceType() {
			var mobile = false;
			//touch on IOS and Android
			var isAndroid = /(android)/i.test(navigator.userAgent);
		  	var isMobile = /(mobile)/i.test(navigator.userAgent);
			if (navigator.userAgent.match(/(iPod|iPhone|iPad)/) || isAndroid || isMobile) {
				mobile = true;
			}else {
				mobile = false;
			}
			return mobile;
		}


		//desktop hover
		function itemHover() {
			$(".reveal-area").hover (
				function () {
					$(this).addClass("reveal-show");
				},
				function () {
					$(this).removeClass("reveal-show");
				}
			);
		}

		//mobile touch
		function itemTouch() {
			$(".reveal-area").on("touchstart", function () {
				$(this).addClass("reveal-show").siblings().removeClass('reveal-show');
			});
		}

		function itemInit() {
			var mobile = deviceType();
			//check device type
			if(mobile == true) {
				//if mobile
				itemTouch();
			} else {
				//if desktop
				itemHover();
			}
		}

		//call function
		itemInit();

	});
}(jQuery));
.reveal-area {
  background: #000;
  width: 100%;
  height: 200px;
}
.reveal-show {
  background: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
	<title></title>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
	<div class="reveal-area"></div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>

Comments