Guide to setting a background image on a div when hovering using jQuery

I'm having trouble adding a background image to this specific div element:

<div class="logo-main"></div>

Here is the script I've been using, but it doesn't seem to be working as expected:

<script type='text/javascript'>
$(document).ready(function(){
    var div = $('.logo-main');
    $('.logo-main').hover(function() {
        div.css({ 'background': 'url(images/slides/glare.png)' }); 
        )};
});
</script>

Does anyone have any suggestions or ideas on how to make this work?

Answer №1

There seems to be a syntax error present in the code below:

$(document).ready(function() {
    var div = $('.logo-main');
    div.hover(function() {
        div.css({
            'background' : 'url(images/slides/glare.png)'
        });
    });
});

A simplified version of the code could look like this:

$(document).ready(function() {
    $('.logo-main').hover(function() {
        $(this).css('background', 'url(images/slides/glare.png)');
    });
});

If you are looking for a hover effect with a different background on hover and normal state, you may want to try this instead:

$(document).ready(function() {
    $('.logo-main').hover(function() {
        $(this).css('background', 'url(images/slides/glare.png)');
    }, function(){
        $(this).css('background', '');
    });
});

For a live demo, you can check out this Fiddle.

Answer №2

Consider using background-image instead (and replace : with ,)..

<script type='text/javascript'>
$(document).ready(function(){
    var div = $('.logo-main');
    $('.logo-main').hover(function() {
        div.css({ 'background-image', 'url(images/slides/glare.png)' }); 
        )};
});
</script>

Answer №3

There is no need to use JavaScript for this task as it can be easily achieved using CSS.

.logo-main {

}

.logo-main:hover {
    background-image: url(images/slides/glare.png);
}

Answer №4

If you want to include a background when hovering over an element, all you need to do is insert the following code into your stylesheet (css)...

.logo-main:hover {
    background: url(images/slides/glare.png);
}

Answer №5

@Alice: I've put together a little demonstration specifically for you. Take a look at the code below:

HTML:

<div class="logo-main"></div>

CSS:

.logo-main{
    background-image:url(http://tommytoy.typepad.com/.a/6a0133f3a4072c970b016301ec8627970d-550wi);
    background-repeat:no-repeat;
    background-position:0 0;
    width:350px;
    height:165px;
}

Jquery Code:


$('.logo-main').mouseover(function() {
   $(this).css('backgroundPosition', '0 100%')
   .mouseout(function() {
       $(this).css('backgroundPosition', '0 0%');
    });
});

Fiddle

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

Customizing the Class of a jQuery UI ui-autocomplete Combobox Container

Is there a way to customize the ui-autocomplete div by adding a custom class? I have several autocomplete widgets on my webpage, and I need to style their drop-downs differently. Since editing the ui-autocomplete class directly is not an option, I am wor ...

Having difficulty styling scrollbars using CSS

There is currently a scrollbar displaying over part of my page when necessary. https://i.stack.imgur.com/48Rbx.png I want to change the styling of the scrollbar to make it less bright and have a transparent background. I attempted to apply some styles, bu ...

Creating a dynamic JQuery navigation menu directly from a MySQL database table

I am looking to dynamically populate the menu on this website (http://www.hv-designs.co.uk/tutorials/sliding_menu/sliding_menu.html) with values from a MySQL table. Essentially, when the user clicks on the top menu button, I want the menu items to be rows ...

Attempting to remove certain selected elements by using jQuery

Struggling to grasp how to delete an element using jQuery. Currently working on a prototype shopping list application where adding items is smooth sailing, but removing checked items has become quite the challenge. Any insights or guidance? jQuery(docume ...

Adding the ability to export CSV files from Bootstrap Table to an Angular 15 project

Struggling to incorporate the Bootstrap-table export extension into my Angular project without success so far. Visit this link for more information Any assistance or examples would be greatly appreciated. Thank you in advance! This is what I have tried ...

What is the best way to make sure my navigation menu adapts to changes in my div size

Just curious, how can I make my navigation menu adjust its width to match the div box? Any help would be appreciated! If you'd like to see an example, here's a jsfiddle link: http://jsfiddle.net/AtM2Q/ Below is the code snippet: <html> & ...

Dispatching current to the default case of the switch statement

Hello everyone, I wanted to share a snippet from my JS file: function passDataToPHP() { endpoint = 'myfile.php'; parameters = ''; parameters += 'action=passData'; parameters += '&myfield='+someV ...

What is the process for configuring a specific timezone in the datetimepicker?

I recently started using the datetimepicker jQuery plugin available at but I am struggling to understand how to incorporate timezone settings. I have reviewed the documentation provided, however, I could not locate any specific instructions regarding tim ...

Create CSS styles that are responsive to different screen sizes and

What is the best approach to ensure that these styles are responsive on any mobile device? nav ul ul { display: none; } nav ul li:hover > ul { display: block; } nav ul { background: #0066cc; background: linear-gradient(top, #0066cc 0%, #bbbbbb 10 ...

The process of organizing and arranging the content that appears on a webpage is in

Seeking a solution to achieve a similar effect like this example. Wanting the sections to transition nicely when clicked on. Should I use a Jquery plugin or implement it with CSS? ...

Issue with jQuery: The click event handler is not firing on elements that were previously hidden

$(document).on('click', '*', function (e) { alert('clicked'); }); I have a script that works for all elements on the current page. However, when I click an element that reveals a previously hidden div element, the click e ...

using variables as identifiers in nested JSON objects

Within my code, there is a JSON object named arrayToSubmit. Below is the provided snippet: location = "Johannesburg, South Africa"; type = "bench"; qty = 1; assetNumber = 15; arrayToSubmit = { location : { type : { 'qty' ...

Exploring the power of JQuery's $.post() function and the magic

In order to utilize the GroupMe API (), the following command is required: $ curl -X POST -H "Content-Type: application/json" -d '{"source_guid": "frgfre", "text":"alala"}' https://api.groupme.com/v3/groups/ID/messages?token=YOUR_ACCESS_TOKEN I ...

Is it possible to create distinct overlapping divs without using absolute positioning?

I'm seeking assistance in developing the view shown below. I am familiar with using position absolute, but I'm wondering if there is a way to achieve this without relying on absolute values. https://i.sstatic.net/m13cl.png ...

Customize Your Form Labels with Bootstrap: Changing Label Color in Forms

I am completely new to using bootstrap, particularly bootstrap 3. The goal I have is to change the color of labels such as "Name", "Email Address", "Phone Number" and "Message" from dark grey to white in the design shown below. https://i.sstatic.net/yDTto ...

inadequately arranged in a line

In Bootstrap 4, I have created this form group that you can view in this fiddle: <div class="m-portlet__body"> <div class="form-group m-form__group row"> <label class="col-lg-2 col-form-label"> Email Address ...

Guide to changing the background color of a table cell using jQuery

I have created an ASP.net webpage with an ASP GridView to showcase a data table. My goal is to implement JavaScript that will change the color of cells containing the value '0' to red. I believe I can achieve this using $("td").each or document. ...

Begin expanding new circles in jQuery from the exact location where the previous ones ended

A captivating circle animation unfolds before your eyes, featuring dark blue circles that materialize at random points and gradually expand. As these expanding circles cover more than half of the screen, their color shifts to a lighter shade of blue. Exper ...

Having trouble with jQuery UI drag-and-drop feature when dropping onto an empty container or

Encountering an issue with the jQuery UI sortable widget where I am unable to drop any item into an empty container. Strangely, when the container already contains an item, it functions perfectly fine. The way I have called the widget is shown below: $(". ...

"Exploring the Power of Internal Hyperlinks in HTML

As I embark on my first website building journey, I am faced with a dilemma regarding internal links. While everything runs smoothly locally, none of the internal links seem to work once the site is live. Take for instance this internal link: <a href =& ...