How to Use Vue.js to Find the Nearest Div Element with a Specific

Below is the HTML code I am working with:

<div id="app">
<div class="image">
    <div class="overlay">
        <p>Some overlay text</p>
    </div>
    <img src="https://placeimg.com/640/480/any" class="img-fluid">
</div>
<div class="info">
    <h6 class="name">Title here</h6>
    <p class="meta">Meta here</p>
</div>
<div class="info-button" @mouseover="addParentClass" @mouseout="removeParentClass">
    Mouse over here!
</div>

I am looking to add certain classes to the image and overlay when a user hovers over the "info-button" div.

Currently, I have achieved this using Vue.js:

let vm = new Vue({
el: "#app",
data:{
    isHovering: false
},
methods: {
    addParentClass (event) {
        event.target.parentElement.children[0].children[1].classList.add('active')
        event.target.parentElement.children[0].children[0].classList.add('overlay-active')

    },
    removeParentClass (event) {
        event.target.parentElement.children[0].children[1].classList.remove('active')
        event.target.parentElement.children[0].children[0].classList.remove('overlay-active')
    },
},
})

Although this works, it involves repetitive JavaScript. I have attempted to simplify it using the following code:

event.target.parent.closest('.overlay'.).classList.add('overlay-active')

Despite trying various selectors like parent, children, and closest, I have not been successful in achieving the desired outcome. How can I make the "closest" selector work in this scenario?

Here's a rough example of my code on Codepen: Link to codepen

Edit: It is worth mentioning that I intend to use this within a loop, so there will be multiple images and I only want the overlay to appear on the current image being hovered over.

Answer №1

VueJS operates reactively, meaning that the data should be the driving force behind any changes to the DOM. It is recommended not to manually manipulate the DOM.

To achieve this, add an 'active' property to the data:

let vm = new Vue({
    el: "#app",
    data:{
        isHovering: false,
        active: false
    },
    methods: {
        addParentClass (event) {
           this.active = true;
        },
        removeParentClass (event) {
          this.active = false;         },
    },
})

Ensure the DOM remains reactive by implementing the following:

<div class="overlay" :class="{'overlay-active': active}" >
    <p>Some overlay text</p>
</div>

For the updated code, visit:

https://codepen.io/samialtundag/pen/Jeqooq

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

A guide on invoking a function within a nested or local function

When the code below is executed in a local function, such as the one inside s3.getObject, it throws an error stating that setState is not a function. s3.getObject({ Bucket: bucket, Key: key }, function (error, data) { if (error != ...

Create a small circle in the bottom left corner with a constrained size

I'm trying to create a circle at the top of the screen on mobile, similar to the image below. The circle should take up a percentage of space, with the rest of the content appearing against a blue background as shown in the image. However, I'm h ...

Angular UI Bootstrap collapse directive fails to trigger expandDone() function

I am currently utilizing UI Bootstrap for Angular in one of my projects, and I have developed a directive that encapsulates the collapse functionality from UI Bootstrap. Here is how it looks: app.directive( 'arSection', ['$timeout', fu ...

Ensure that you decode the URL before making any changes to the location in a

Hi everyone, I'm facing an issue and need your help. Let's say we have a URL like site.com/post?comments=1,2,3,4. When I paste it into the browser address bar, my app opens and decodes the URL to site.com/post?comments=1%2C2%2C3%2C4. How can I re ...

Deconstructing arrays in the req.body object in a Node.js Express application

Received an array in the request body as follows: [ { "month" : "JUL", "year" :"2018" }, { "month" : "JAN", "year" :"2018" }, { "month" : "MAR", "year" :"2018" } ] This array consists of two parameters (month:enum and year:string). ...

AngularJS single page applications experiencing issues with loading scripts and stylesheets upon page reload

Homepage Setup : <ng-view></ng-view> Angular Routing Configuration : when('/', { url: '/', templateUrl: 'site/home', controller: 'indexController' }). when(&apos ...

What is the correct way to customize colors for specific components in Material-ui?

Struggling with theming in Material-UI, particularly when it comes to customizing element colors. Some elements default to 'theme.palette.main.dark' and I want to override this behavior. For example, the TextField and SpeedDial components automa ...

Optimizing Input Type Date (Calendar) Reactstrap for Minimum and Maximum Values

I'm in the process of integrating a Calendar feature into my website for scheduling appointments, and I need it to start from today and onwards. How can I achieve this using the Reactstrap component? I couldn't find any relevant information in th ...

Hide panel when button is clicked - bootstrap

Is it possible to make a panel collapse by clicking a regular bootstrap button? Below is the code snippet: <div class="panel panel-primary" style="border-color: #464646;"> <div class="panel-heading" style="border-color: #BBBBBB; height: 35px; ...

Having trouble loading CSS and JavaScript files in CodeIgniter?

In my project, I am utilizing Bootstrap as a template. However, when attempting to access Bootstrap in Codeigniter, the page fails to load the CSS and JavaScript files. I have included the URL in autoload.php $autoload['helper'] = array('url ...

Ruby on Rails and JSON: Increment a counter with a button press

How can I update a count on my view without refreshing the page when a button is clicked? application.js $(document).on('ajax:success', '.follow-btn-show', function(e){ let data = e.detail[0]; let $el = $(this); let method = this ...

Is there a method to hide an HTML form completely?

Is there a way to quickly hide an HTML form from a webpage once the submit button is clicked and replace it with the result of a .php file in the most efficient manner possible, with minimal code? ...

Is spine.js truly capable of 'streamlining' POST requests?

I recently came across a post by Alex Maccaw, where he discusses the challenges of sending Ajax requests in parallel: Maccaw explains that if a user creates a record and quickly updates it, two Ajax requests are sent simultaneously - a POST and a PUT. How ...

Align text to the left of a button with Bootstrap 4

Currently, I have two buttons stacked on top of each other. I'm attempting to include some text to the left of the bottom button, but I am encountering two obstacles: The first issue is that it creates a white round-ish shape around my top button w ...

Storing data from a massive JSON array into a separate array using a specific condition in JavaScript

Dealing with a large JSON array can be challenging. In this case, I am looking to extract specific objects from the array based on a condition - each object should have "dbstatus":-3. data = [{"id":"122","dbstatus":-3},{"id":"123","dbstatus":"-6"},{"id" ...

What is the best way to select a clicked span element within a div using JQuery and then adjust the spans before and after it

<div> <span>A</span> <span>B</span> <span>C</span> <span>D</span> </div> If a user clicks on one of the spans within the div, I want to apply styles (such as text color) to that span and all prec ...

Can the URL be updated in Vue Router without navigating to a new page?

I am working on a Nuxt.js website and trying to implement a "Load more" button on the /catalog page. When clicking on the button, I want to load more products without navigating to a new URL like /catalog/page_2 (?page=2 is not an option). If I use $router ...

Changing my PHP contact form from method GET to POST is causing it to malfunction

Feel free to check out my contact form on benlevywebdesign.com, located at the bottom of the page. <form id="form1" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="text/plain" method="get"> <fieldset> ...

Once the Ajax request is finished, the cookie deletion function ceases to function

When the website loads, a cookie is generated using PHP before any other content or headers are sent. This is done with the following code: $steam_login_verify = SteamSignIn::validate(); if(isset($_COOKIE['userid'])) { //work with cookie va ...

Vue.js - the lightweight JavaScript framework without any dependencies mentioned

I'm currently developing a project using Django (Python-based Web Framework) with Vue.js as the front-end framework. Most of the resources I've come across regarding Vue.js mention Node, especially for setting up the development server. I'm ...