简体   繁体   中英

How to make a hover function ALSO a click function using javascript

I have a tooltip that can be seen below, at the moment it reveals the tooltip only on hover, but I want it to reveal the tooltip when both hovering and clicking (for touch screen devices) could somebody please show me how?

My JSFiddle

My javascript code

<script type="text/javascript">
$(function(){
  $("ul.thumb li").hover(function() {
  $(this)
    .css('z-index', '10')
    .find('img').addClass("hover")
    .stop()
    .animate({
       marginTop: '-150px',
       marginLeft: '-150px',
       top: '50%',
       left: '50%',
       width: '300px',
       height: '300px',
       padding: '20px'

     }, 200, function() {

        var $this = $(this),
        h = $this.height();
        $caption = $('<div class="caption">' + this.title  + '</div>')
            .css('top', h.toString() + 'px');
            $this.after($caption);

      }); 

   }, function() {

 $('.caption').remove();
 $(this)
.css('z-index', '0')
.find('img').removeClass("hover")
.stop()
.animate({

    marginTop: '0',
    marginLeft: '0',
    top: '0',
    left: '0',
    width: '200px',
    height: '200px',
    padding: '5px'

 }, 400);
});
});
</script>

You can use jQuery .on() method to bind a handler to multiple events...

First of you need to name the two functions. Then you can use .on() as follows:

$("ul.thumb li").on('mouseover touchstart', show);
$("ul.thumb li").on('mouseleave touchend', hide);

Updated JSFiddle

First, refactor and rename your hover in and out function:

function showTooltip(){
  $(this)
    .css('z-index', '10')
    .find('img').addClass("hover")
    .stop()
  // etc...

}

function hideTooltip(){
  $('.caption').remove();
  $(this)
    .css('z-index', '0')
    .find('img').removeClass("hover")
    .stop()
  // etc...
}

Then instead of using the hover shorthand, use the mouseenter and mouseleave events to listen the hovering:

$("ul.thumb li")
  .on('mouseenter', showTooltip)
  .on('mouseleave', hideTooltip);

If you want to show the tooltip for touch events, just add the touchstart event to it: I guess you want to tap to both open and close the tooltip.

$("ul.thumb li")
  .on('mouseenter touchstart', showTooltip)
  .on('mouseleave touchstart', hideTooltip);

You can create a function, let's call it activate :

function activate(that) {
    //Your code here
}

and then use it like this:

$("ul.thumb li").hover(function() {
    activate($(this));
});

$("ul.thumb li").click(function() {
    activate($(this));
});

Note, that activate will hold the commands you need to process in those events. Also, in activate , try to make sure that you are using that instead of this .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM