What is preventing hover from working correctly?

I'm having trouble getting images to display when hovering over text. Can anyone offer suggestions on what might be causing this issue? The images are being downloaded when clicked, so I know they're in the correct path. I've checked for common typos and errors online, but couldn't find anything useful. I've gone through it multiple times and even used a linter, but still can't pinpoint the problem.

Any help would be appreciated. Thank you in advance.

$(function () {
$('img[data-hover]').hover(function () {
    $(this).attr('tmp', $(this).attr('src')).attr('src', $(this).attr('data-   hover')).attr('data-hover', $(this).attr('tmp')).removeAttr('tmp');
}).each(function () {
    $('<img />').attr('src', $(this).attr('data-hover'));
});
});

$(document).ready(function () {
$('a.tip').imgPreview({
    containerID: 'imgPreviewWithStyles',
    /* Change srcAttr to rel: */
    srcAttr: 'rel'
});
});

(function ($) {
$.expr[':'].linkingToImage = function (elem, index, match) {
    // This will return true if the specified attribute contains a valid link to an image:
    return !!($(elem).attr(match[3]) && $(elem).attr(match[3]).match(/\.(gif|jpe?g|png|bmp)$/i));
};

$.fn.imgPreview = function (userDefinedSettings) {

    var s = $.extend({

        /* DEFAULTS */

        // CSS to be applied to image:
        imgCSS: {},
        // Distance between cursor and preview:
        distanceFromCursor: { top: 10, left: 10 },
        // Boolean, whether or not to preload images:
        preloadImages: true,
        // Callback: run when link is hovered: container is shown:
        onShow: function () { },
        // Callback: container is hidden:
        onHide: function () { },
        // Callback: Run when image within container has loaded:
        onLoad: function () { $(this).delay(5000).fadeOut(500); },
        // ID to give to container (for CSS styling):
        containerID: 'imgPreviewContainer',
        // Class to be given to container while image is loading:
        containerLoadingClass: 'loading',
        // Prefix (if using thumbnails), e.g. 'thumb_'
        thumbPrefix: '',
        // Where to retrieve the image from:
        srcAttr: 'rel'

    }, userDefinedSettings),

    $container = $('<div/>').attr('id', s.containerID)
                    .append('<img/>').hide()
                    .css('position', 'absolute')
                    .appendTo('body'),

    $img = $('img', $container).css(s.imgCSS),

    // Get all valid elements (linking to images / ATTR with image link):
    $collection = this.filter(':linkingToImage(' + s.srcAttr + ')');

    // Re-usable means to add prefix (from setting):
    function addPrefix(src) {
        if (src !== null) {
            return src.replace(/(\/?)([^\/]+)$/, '$1' + s.thumbPrefix + '$2');
        }
    }
    if (s.preloadImages) {
        (function (i) {
            var tempIMG = new Image(),
                callee = arguments.callee;
            tempIMG.src = addPrefix($($collection[i]).attr(s.srcAttr));
            tempIMG.onload = function () {
                $collection[i + 1] && callee(i + 1);
            };
        })(0);
    }

    $collection
        .mousemove(function (e) {

            $container.css({
                top: e.pageY + s.distanceFromCursor.top + 'px',
                left: e.pageX + s.distanceFromCursor.left + 'px'
            });
        })
        .hover(function () {

            var link = this;
            $container
                .addClass(s.containerLoadingClass)
                .show();
            $img
                .load(function () {
                    $container.removeClass(s.containerLoadingClass);
                    $img.show();
                    s.onLoad.call($img[0], link);
                })
                .attr('src', addPrefix($(link).attr(s.srcAttr)));
            s.onShow.call($container[0], link);

        }, function () {
            $container.hide();
            $img.unbind('load').attr('src', '').hide();
            s.onHide.call($container[0], this);
        });

    // Return full selection, not $collection!
    return this;
};

})(jQuery);

Answer №1

Ensuring that your selector is functioning correctly is crucial. Without viewing your HTML, it's difficult to determine for certain. The jQuery selector selector[x=?] functions by identifying all elements that match selector with the attribute x="?".

For example, the selector img[height=100] will target all images with a height attribute set to 100.


In your specific case, you are using the selector img[data-hover], which highlights images with a defined data-hover attribute, such as:

<img src="..." data-hover=""/>

The actual value of the attribute doesn't matter, as long as it exists for the selection to function. If your aim is simply to attach a hover event to the images, you can achieve this with the .hover() method alone.

$("img").hover(function(){});

JSFiddle

This JSFiddle demonstration illustrates the points mentioned earlier. Both images experience reduced opacity on hover because their heights are specified. However, only the bottom image undergoes inversion on hover due to its height being set at 200.

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

Creating an image from the contents of a div is necessary in order to visually

I am looking to develop a software that can: receive text input from the user and place it in a specific div allow users to adjust font, color, and size based on their preferences enable image uploads as background save all customizations and send them v ...

The CSS styles are not being applied correctly in the HTML document

I have this snippet in my .css file: .attachment-label { font-size: 10px; font-style: italic; color: rgba(0,0,0,.5); } When I try to use it in my HTML like this: <div class="card-body"> <span class=" ...

Reposition a Single Item on the Top Menu to the Right

I'm new to HTML and CSS and I need help aligning the "Login" item to the right. I'm trying to create a horizontal menu bar, but not sure if I'm approaching it correctly. Something similar to this: How I want it to be Here is the code I have ...

An SVG with a single enigmatic path/shape featuring a perplexing left margin or empty space. Not contained within an

I created a unique shape in Illustrator and adjusted the artboard to fit the shape perfectly, eliminating any excess white space. I double-checked this process to ensure accuracy. Upon opening the design in Chrome and inspecting it, I noticed that when ho ...

Update the table in a few moments

I am struggling to refresh my table every 5 seconds but haven't been successful. <table width="100%" class="table table-striped table-bordered table-hover" id="dataTables-example"> <thead> <tr> <th>Number</th> ...

Tips for saving the visibility status of a <div> in your browser bookmarks?

Currently, I am in the process of developing a single webpage (index.html). The navigation bar at the top includes links to hash references (DIV IDs). If JavaScript is enabled, clicking on these links triggers a JavaScript function with the onclick attribu ...

AngularJs - Customizable dynamic tabs that automatically adapt

Below is the HTML code snippet: <div> <ul data-ng-repeat ="tab in tabs"> <li data-ng-class="{active: tab.selected == 'true'}" message-key="Tab"> </li> </ul> </div> As shown ...

Using Phonegap to connect to MySQL Database

I am exploring the use of PhoneGap (Cordova3) and my goal is to create a screen that instantly pulls data from MySQL when it loads, allowing users to click on the results to navigate to another page with more details. Do I need to implement jQuery for thi ...

Tips for showcasing varied information on Morris Chart

I am working with a Morris chart that is populated with a collection of data, each item containing 6 different data values. My goal is to switch between displaying two different sets of data. For example, I want to show the 'Target' data always ...

Tips for setting up the Top Menu and Left Side Menu in your system

You're looking to incorporate both the Top Menu and Left Side Menu. The top menu should remain fixed at the top of the page. Implementing the Left Side Menu below the Top Menu has been a challenge. It's currently covering the top menu, which is ...

Tips for displaying animations only the first time using HTML and CSS:

Upon the initial visit to my website, a captivating animation introduces itself with the words "Hello. I'm Bob" as it gracefully fades into view. Navigating through the menu bar allows users to explore different sections of the site. However, there ...

What could be causing my elements to shift out of place?

Here is the box I created: BOX Now, I want to position another box near the input of the BET box. <div id="x2"></div> <!-- HTML ---> /* CSS */ #x2{ width: 40px; height: 40px; background: cornflowerblue; } The layout after ...

Position the div alignment to the top within the table cell

I'm having trouble aligning the div under the header to the right. Here is my HTML code and a photo for reference: HTML Code: <td> <div class="schedule-content"> <div class="timestamp& ...

Ways to save an array in my database with each value occupying a single row

Is it possible for the form to be submitted with an array of checked values when a user clicks on a checkbox and saves? Each checked value should be saved in the database as a single row. I'm not sure if this is achievable, but I believe you might hav ...

Location tracking functions only operational when using the local host

I managed to successfully integrate geo-location on my website while testing it on localhost. But, when I uploaded the website to an online server, I encountered a problem. I started receiving a bool(false) error message. Geo.php <?php class G ...

Steer clear of posting additional content that might bump the existing content further up

How can I keep the search bar centered on the screen, even when content is added below it? Here's a screenshot illustrating the issue: https://i.stack.imgur.com/7pQ1q.png The text in the image is causing the search bar to move up, but I want the sea ...

Issues with Twitter-Bootstrap Modal Functionality

After creating a modal dialogue: <a href="#myModal" role="button" class="btn" data-toggle="modal" id="LaunchDemo">Click here to launch the demo modal</a> <!-- Modal --> <div id="myModal" class="modal hide fade" tabindex="-1" role="di ...

Firefox does not support the event

// This function makes rows draggable within a table by utilizing mouse events. // It handles the drag initiation, movement, and stopping of the drag operation. makeRowsDraggable: function() { var dragInitiated = false; var startPageX, startPageY ...

Dynamic Email Design

Currently, I am working on coding an HTML email that needs to be optimized for perfect rendering on all mobile devices. While I have expertise in coding emails for desktop and ensuring compatibility with various email clients and browsers, the challenge no ...

A JavaScript function that smoothly scrolls an element into view while considering any scrollable or positioned parent elements

I needed a function that could smoothly scroll a specific element into view with some intelligent behavior: If the element is a descendant of a scrollable element, I wanted the ancestor to be scrolled instead of the body. If the element is within a posit ...