Using Vue.js to update the v-bind:style when the mouse hovers over the element

I am working with a span element that displays different background images based on certain conditions.

Here is the HTML:

  <span
      v-if="type"
      :style="styles"
    >
  </span>

In the computed properties section:

styles() {
  return {
    "background-image": `url(${require(`../assets/images/${this.type}.png`)})`,
    height: "30px",
    width: "100%",
    display: "block",
    "background-size": "contain",
    "background-repeat": "no-repeat",
    "background-position": "center",
  };
},

Additionally, I have another condition to display a different background image on mouseover.

stylesOnHover() {
  return {
    "background-image": `url(${require(`../assets/images/${this.type}-hover.png`)})`
  };
},

I attempted to add

@mouseover="stylesOnHover"
in the HTML span, but it resulted in an error :

[Vue warn]: Error in v-on handler: "TypeError: handler.apply is not a function"

Could someone guide me on how to modify the background image property on mouseover? Thank you.

Answer №1

When you return an object from your function, the style may not be properly applied to the element. One solution is to use a boolean in your state to control which styles are applied to the element, and then handle the rest in your template. Another option is to let the boolean dictate whether to merge the style in your computed styles.

Answer №2

Look no further, this is the ultimate solution you've been seeking here. Make sure to use the background-image property instead.

If you are determined to utilize mouseover effects, then stylesOnHover must be implemented as a method or computed function that returns a function. This will allow you to dynamically change the backgroundImage of event.target.style within that method/function.

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

Can you confirm the mobile type, please? Using JavaScript to display a div only once based on the mobile type

Is there a correct way to determine the type of mobile device I'm using? Are there alternative methods to check for the mobile type? Take a look at my approach in the code below. How can I test this using a tool? Does anyone have insights on checki ...

Mobile page sliding mechanism

My website contains a div that is mostly off the page, but on hover it translates onto the main page. You can check out my website. However, this method doesn't work well on mobile devices. Hovering is not effective and I often have to click multipl ...

Tips for creating a mobile-responsive React + MUI component

A React component utilizing Material-UI (MUI) has been created and I am working on making it mobile responsive. The current appearance is as follows: https://i.stack.imgur.com/8z0T8.png My goal is to have it look like this: https://i.stack.imgur.com/L8g ...

Is there a jQuery function that can produce repeated output and append content with each successive click?

Attempting to implement a dynamic searchbar with various parameters has led me to explore using jQuery to load and clone the searchbar file in order to append it to the body dynamically. I have made several attempts to modify selectors without achieving t ...

SolidJS: "Value not recognized"

I have successfully retrieved the JSON value from the API path. Flask Code app = Flask(__name__) CORS(app) @app.route("/cats-matches", methods=['POST']) def cats_matches(): person = {"name": "John"} #This is not ...

Design a Hover Mega Menu - click outside to close

Although there are similar topics on stackoverflow, the code I have is different from them. I am trying to achieve the following: If I click on the search box (the white square on the site), my search box should open If I open the search box and then cl ...

What is the best approach for manipulating live data in localStorage using ReactJS?

I am working on creating a page that dynamically renders data from localStorage in real-time. My goal is to have the UI update instantly when I delete data from localStorage. Currently, my code does not reflect changes in real-time; I have to manually rel ...

Error message thrown by node express.js indicating that response headers cannot be reset once they have been sent

As a newcomer to both node and express, I may be making a silly mistake. If you want to see the complete source code, please visit: https://github.com/wa1gon/aclogGate/tree/master/server logRouter.get("/loggate/v1/listall", function(req, res) { let ...

Adjusting the width of a div element using a button

I am currently diving into the world of JavaScript, React, and Node.js. My current challenge involves attempting to adjust the width of a div element using a button. However, I keep encountering the same frustrating error message stating "Cannot read prope ...

Tools for parsing command strings in NodeJS

Currently, I'm utilizing SailsJS for my application. Users will input commands through the front-end using NodeWebkit, which are then sent to the server via sockets. Once received, these commands are parsed in the back-end and a specific service/cont ...

A guide on updating the Date Textfield value in Material UI

In my data structure, I have an array of objects with unique ids and date values. For instance, the array named stepDates might appear like this: [ { id: 1, date: "2021-07-23" }, { id: 2, date: null }, { id: 3, d ...

Dealing with Database Timeout in Express JS

I have been trying to extract SQL query execution into a separate file to prevent code repetition, but I am facing timeout issues during execution. var mysql = require('mysql'); const connectionData = { host: 'localhost', user: ...

What is the best way to filter out empty arrays when executing a multiple get request in MongoDB containing a mix of strings and numbers?

I am currently working on a solution that involves the following code: export const ProductsByFilter = async (req, res) => { const {a, b, c} = req.query let query = {} if (a) { query.a = a; } if (b) { query.b = b; } if (c) { ...

Integrate, Delay, Experimentalize, and Attach components

This inquiry might lean more towards a general browser/javascript discussion rather than a focused prototype question, but I believe this community possesses a deep understanding of javascript and browsers. With that said, here is my query: If the followi ...

There was a TypeError encountered while trying to read properties of undefined in Next.js version 13

I've encountered a problem in the title with my post API endpoint that I created in Next.js. The purpose of my endpoint is for form submission, where I gather inputs and send them to my email. Currently, my code successfully sends the email and I rec ...

Setting ng-click on a custom element directive in Angular 1.x: A guide

Within this code, I have assigned ng-click to a custom element directive with the expectation that clicking the rendered text would trigger an alert saying "Worked from directive!" However, the functionality does not seem to be working as intended. Althou ...

The persistent issue of window.history.pushstate repeatedly pushing the identical value

I need some assistance with my Vue application. I am trying to update the URL when a user clicks on an element: const updateURL = (id: string) => { window.history.pushState({}, '', `email/${id}`); }; The issue I'm facing is th ...

Refreshing a specific area on a webpage through the use of Ajax technology

I need to update a specific part of my webpage when a user clicks on the 'clear' button. I currently have some code that I borrowed from another answer I found on this site: $('.clear').click(function () { $.ajax({ url: "", ...

Unexpected results: jQuery getJSON function failing to deliver a response

I am facing an issue with the following code snippet: $.getJSON('data.json', function (data) { console.log(data); }); The content of the data.json file is as follows: { "Sameer": { "Phone": "0123456789", }, "Mona": { "Phone": ...

Floating dropdown within a scrolling box

How can I ensure that the absolute positioned dropdown remains on top of the scrollable container and moves along with its relative parent when scrolling? Currently, the dropdown is displayed within the scrollable area. The desired layout is illustrated i ...