What is the best way to switch the click event function in jQuery?

I would like to share some code with you:

HTML

<a href="#" class="button">button</a>

<div class="holder">

    <img src="http://placehold.it/350x150" />
    <div class="content">
        <h3>hello there</h3>    
        <a href="#">view more</a>        
    <div/>    

</div>

CSS

.holder {
    margin-top: 130px;
    position: relative;
}
img {    
    position: relative;
    display: block;
    transition: -webkit-transform 0.5s;
    transition: -moz-transform 0.5s;
    z-index: 10;
}
.content {
    background: blue;
    height: 100%;
    color: white;
    z-index: 1;
    position: absolute;
    top: auto;
    bottom: 0;
}
a {
    color: white;
    background: red;
    padding: 10px;
}

.holder:hover img {
    -webkit-transform: translateX(90px);
    -moz-transform: translateX(90px);
}
.button {
    background: green;
    position: absolute;
    top: 10px;
}

JQuery

   if (Modernizr.touch) {
    alert("touch support");
}

else {
     alert("no touch support");

    $('.button').toggle(
     function(){
             $('img').css({
              '-webkit-transform' : 'translateX(90px)',
               '-moz-transform' : 'translateX(90px)'                 
             }); 
    },
    function(){
     $('img').css({
             '-webkit-transform' : 'translateX(-90px)',
             '-moz-transform' : 'translateX(-90px)'                 

            }); 
    });
}

The intention behind the code is to change the image position on hover for non-touch devices and replicate this behavior using jQuery for touch devices due to limitations of the hover event on such devices.

My queries are as follows: 1) Is this code accurate? 2) The jQuery snippet seems to make the button disappear instead of moving the image position.

You can view the CSS implementation here: jsfiddle-css

Here is the attempt to replicate it with jQuery, which is currently not functioning as expected: jsfiddle with jquery

Answer №1

Perhaps one way to accomplish this is:

if (Modernizr.touch) {
    alert("touch support");
} else {
    alert("no touch ");
    var cssChanged = false; // remember whether the css has been modified
    // Please note: Instead of true/false, a counter could be used as well to trigger an action every Nth click
    $('.button').click(function(){
        if(cssChanged===false)
            $('img').css({
                 '-webkit-transform' : 'translateX(90px)',
                 '-moz-transform' : 'translateX(90px)'                 
             });
            cssChanged = true; // mark that css has been changed
        }
        else{
          $('img').css({
                 '-webkit-transform' : "",
                 '-moz-transform' :""                
             });
            cssChanged = false; // reset variable back to unchanged state
        }
    });
}

Answer №2

Just a heads up

If you're facing a problem, consider using the jQuery Migrate plugin:

Implementing the plugin is simple; just add it right after loading jQuery in your script, like this:

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.1.1.js"></script>

For more details, refer to the jQuery Migrate documentation.

Check out the FIDDLE DEMO

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

retrieve the src value of an image using jquery

I found this helpful example at the following link: This example allows me to retrieve the index number of the current image. Here is the code I am using: $('#preview_images_gallery').bxSlider({ onAfter ...

Pass the object either in JSON format or as a variable using the drag and drop feature

Here's a quick question: when using the Drag and Drop system, I'm not sure which method is better. Is it more efficient to : utilize setData and getData to transfer a JavaScript object? (Utilizing JSON conversion since setData only passes st ...

Using JQuery AJAX to successfully retrieve data and then smoothly applying the fadeIn

Utilizing AJAX, I am loading survey content into a container on a webpage. As part of the transition, I have implemented a fadeOut effect on the container, followed by fadeIn once the content is loaded. This method functions correctly for pages 1-4; howeve ...

SortTable - Refresh Dropdown Filter in Header After Adding Row to Table

My tablesorter table initially displays two entries in the "License" Filter. https://i.sstatic.net/4XODb.png If I dynamically add a row, the table now looks like this: https://i.sstatic.net/vMMYc.png I have attempted to update the table using the follow ...

Adding an hour to a time value with preg_replace: A step-by-step guide

On my page, I display times like this: 10:00am. Now, I'm looking to add one hour to each of these displayed times. I've managed to create a regular expression that helps locate the times in the format required, but I'm stuck on what steps to ...

Updating ng-repeat in a different controller with AngularJS

My coding task is quite straightforward. I am trying to refresh an ng-repeat in my AngularJS application. Here is the HTML code snippet: <div class="quick-actions" ng-controller="DashboardController"> <div class="ui accordion segment"> ...

Sending formdata containing a file and variables via $.ajax

I've been working on a jquery file upload project based on a tutorial I found here: . The tutorial is great and the functionality works perfectly. However, I'm looking to add more control and security measures for user image uploads, such as inco ...

Displaying a PHP variable within an HTML tag that has been previously output within a PHP block

I'm struggling with printing a variable that was already echoed in a php tag within an html tag. Specifically, I want to print the variable $A in an h1 tag. Here is my code: <?php while($pr = mysql_fetch_assoc($qAccess)) { $ ...

Set up a custom JavaScript function to automatically refresh a webpage

I am in the process of setting up a JavaScript function to refresh on a specific webpage. The website utilizes an overarching JS and CSS framework, but I desire this particular function to load in a unique manner. The JS function within the framework dyna ...

Is it possible to change the input type of 'time' to a string when utilizing ng-change in AngularJS?

Is there a way to convert a time input into a string or a timestamp for Firebase support? For instance, the code below will not function correctly due to the time input type. HTML <html ng-app='app'> <head> <script src="http ...

Steps for inserting a JSON Array into a database

I have a dropdown menu that displays different options based on the selection from another dropdown. The data for each dropdown is fetched from the database and I need to insert the selected values into a new table in the database. All the necessary code ...

What is the best way to use jQuery to toggle the visibility of a background?

Check out my CSS below: #load-icon { background: url(/Images/loaders/mask-loader.gif); background-repeat: no-repeat; z-index: 99; width: 32px; height: 32px; z-index: 99; margin-top: 9px; margin-bottom: 9px; margin-right: 5px; ...

Slanted lines HTML CSS

I am encountering an issue with my HTML and CSS coding. The design requires a zig-zag "border" at the top and bottom of the page, creating a white paper space in between. The paper needs to be positioned underneath the zig-zag borders. Currently, this is ...

Link Cordova 9 mobile application with a Java Web Service through Ajax request

I recently started working with Cordova and have installed version 9 for development on Android Studio. I am facing an issue with a simple AJAX call to my Java web service layer. Despite whitelisting the URL in config.xml, I am unable to connect to my web ...

Swapping out standard social media icons for personalized images

I'm interested in learning how to customize my social media icons with my own images. Instead of using the standard Facebook Like button or Twitter follow button, I want to use my own images while retaining the same functionality. Websites like Buzz ...

The problem lies in the occurrence of error 404 specifically when a delete request is

Just starting out with node JS and running into a problem regarding a Delete Request returning a 404 error. The connection to the DB is working fine, as I can add entries using a post request. It's specifically the delete request that's causing i ...

Seamless changes with graceful fades while transitioning between classes

Is it more efficient to handle this in CSS than using jQuery? I'm not entirely sure. If anyone has a solution, that would be greatly appreciated. However, I am currently facing an issue with the jQuery method I have implemented. It successfully fades ...

Having Problems with Facebook's "og:image" not refreshing?

I'm having trouble updating the image on my website, www.lux-boutique.co.uk. Despite my efforts, the image displayed on Facebook remains unchanged. Any suggestions? Even after using the Facebook debugger tool, the old image persists. I've delet ...

What might be causing the status problem to not display correctly?

My toggle feature to switch between no issue and issue is not displaying the status correctly. Despite trying to troubleshoot, I can't figure out why the issue section is not showing up. <!DOCTYPE html> <html> <script src="https://aj ...

Tips on automatically populating a textbox without the need for a button click

I am currently using the following code: <input type="text" value="<?php echo empty($this->session->store['actual_info']['actual_total_marketing_budget']) ? '' : $this->session->store['actual_info' ...