If a parent element contains a specific class, then this class should also be added

Is there a way to dynamically add a class to an img element for animation purposes, based on the parent of 'image-reveal-check' having an active class?

To clarify: The parent class does not always have 'active', it is only added when the element comes into view.

HTML Code Snippet

<div class="active">
    <div class="image-reveal-check">
        <div class="image-reveal-inner">
            <img>
        </div>
    </div>
</div>

jQuery Code Snippet

if ($(".image-reveal-check").parent().hasClass('active')) {
    $(".image-reveal-inner img").addClass('image-reveal-start');
}

Answer №1

To activate the event, simply include the active class within the div.

In this example, I have added the class through a button click, but in your scenario, you can trigger it when the element enters the viewport.

$("#addClassActive").click(function() { 

//Upon clicking the button, the active class is added to the div. In your case, this action should be performed when the element enters the viewport
    $('.image-reveal-check').parent().addClass('active').trigger('classChange');
});

$('div:eq(0)').on('classChange', function() { //Locating the root div, finding the image, and applying the specified class
     $(this).find("img").addClass("image-reveal-start")
});
.image-reveal-start
{
 border: solid 1px red;
 width: 50px;
 height: 50px;
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <div class="image-reveal-check">
        <div class="image-reveal-inner">
            <img src="#" title="I am Image!" alt="I am Image!" />
            
            <button id="addClassActive">Add Class</button>
        </div>
    </div>
</div>

Answer №2

Give this a try, it's functioning properly. You can view the results in the Code Snippet section.

$( document ).ready(function() {
console.log( "ready!" );
if ($(".image-reveal-inner").parent().hasClass('image-reveal-check')) {
$(".image-reveal-inner img").addClass('image-reveal-start-add');
console.log( "done!" );
}
});
<div class="active">
    <div class="image-reveal-check">
        <div class="image-reveal-inner">
        ASD
            <img alt="img title">
        </div>
    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>

Answer №3

To achieve the desired effect, you don't need to rely on JavaScript at all. Simply include a rule in your CSS code like this:

div.active .image-reveal-inner img { }

The following example demonstrates that only the first image with a parent containing the class active will have the specified animation, while the second image without the active class will not.

div.active .image-reveal-inner img {
  position: relative;
  -webkit-animation: floatBubble 2s normal ease-out;
  animation: floatBubble 2s normal ease-out;
}

@-webkit-keyframes floatBubble {
  0% {
    right: 300px;
  }
  100% {
    right: 0px;
  }
}

@keyframes floatBubble {
  0% {
    right: 300px;
  }
  100% {
    right: 0px;
  }
}
<div class="active">
  <div class="image-reveal-check">
    <div class="image-reveal-inner">
      <img alt="img title" src="https://i.sstatic.net/2lRQ9.png">
    </div>
  </div>
</div>

<div>
  <div class="image-reveal-check">
    <div class="image-reveal-inner">
      <img alt="img title" src="https://i.sstatic.net/2lRQ9.png">
    </div>
  </div>
</div>

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

javascript the unseen element becomes visible upon page loading

my website has the following HTML snippet: function getURLParameters() { var parameters = {}; var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { parameters[key] = value; }); return param ...

Retrieve a specified child object within its parent object using a string identifier

I have a situation where I need to create a JavaScript function that can extract a child object from a parent object based on a specific string identifier. Here is an example of what I'm looking for: function findChild(parent, name) { return par ...

Tips for creating a responsive div that contains both an image and description, including automatically resizing the image to fit the

#content { background-color: #ACAE4C; float: right; display: inline-block; padding: 0; } <div id="content"> <div class="pic"></div> <div class="desc"></div> </div> I need assistan ...

Can PHP offer a more streamlined method for displaying the chosen item from SQL in a dropdown menu?

I am attempting to extract the name of the country from the database and display the chosen country. The current method I am using involves listing all 193 countries individually, which seems inefficient. Is there a simpler way to accomplish this task? & ...

jQuery: Display a modal window when a table is selected

I am looking to implement a dialog box opening feature when a table is selected on a webpage. Currently, I am able to achieve this by using the id element of the table and mouseup function. However, this solution does not work for tables that do not have t ...

How to bind clickable labels to a model using a radio button in .NET Core?

Trying to create a radio button list in asp.net core that is bound to a model while also having clickable unique labels associated with each option. Currently, here is the code snippet: <fieldset> <div> <span> ...

Error with REST service and browser history in ReactJS

I am currently developing my first Java application, which is a REST service built with Spring Boot. It utilizes technologies such as WEB, REST, JPA, Thymeleaf, and MySQL. The API is fully functional, but I wanted to enhance it with a user interface. After ...

Can the dimensions of an element be determined before adding it to the DOM using HTML, CSS, and JS?

My current task involves dynamically creating HTML elements using JavaScript. Here is an example: var newElement = document.createElement("div"); newElement.innerHTML = _data[i].content; newElement.className = "custom"; When the ...

Updating a URL for all users using React/Next.js and Firebase: a guide to refreshing the page

I am currently developing a Next.js application with a Firebase backend and have encountered an issue. In my setup, users can create sessions that others can join, but only the creator of the session can "start" it, triggering a state change. I need all us ...

The process of retrieving request data from axios.get and storing it in the Redux store

Recently delving into Redux, I'm curious about how to retrieve request data from a GET method. Upon mounting the component, you can use axios to send a GET request to '/api/v3/products', passing in parameters like pageNumber and pageSize. ...

obtaining the complete file path from fileupload in Java servlet via an HTML form

How do I retrieve the full file path from HTML in a servlet for uploading? When I try to print the filename, it only displays the name without the full path. I am unable to figure out how to obtain the complete path and encountering this error message. fi ...

Retrieve the Span class value contained within a Select Option

I realize it may appear repetitive, but it is not. This is the appearance of my select: <select id="avpMy4Y7E4cH_-iIRmmAK6-2GsEOu6Sjr-0-0"> <option value="1Ltr [ <span class=money>Rs.1,495.00</span> ]">...< ...

Maintain selected values in a dropdown list that is generated dynamically

I am currently revamping an outdated webpage that pulls data from a database. My main objective is to implement the functionality to let users narrow down their search by selecting certain values. To achieve this, I have developed a dynamic dropdown list ...

Ways to incorporate useEffect within a function or the other way around

Currently, I am facing an issue with my code. I have a function that handles the onChange event to retrieve the input value. Additionally, I have another function that searches for items in an array based on the value from the input and then renders a comp ...

Issue: TypeError - 'process.env' can only accept a configurable while installing windows-build-tools

Unable to successfully download installers. Encountered an error: TypeError: 'process.env' can only accept a configurable, writable, and enumerable data descriptor. I attempted to resolve this issue by running the command npm install --global wi ...

Is it possible to align text to an image within an input text field?

<input type="text" class="usernm" style="color:black;font-weight: bold;outline-width: 0;" id="username" /> I have a question about styling HTML. I am attempting to include an icon inside a text field, but I'm strugglin ...

The beforeCreate function is failing to execute when a new user is being created

I'm currently working with sailsjs version 0.11.0. My goal is to ensure that when a new user is created, their password is encrypted before being stored in the database. To achieve this, I have implemented the use of the bcrypt library. In my User.js ...

Assigning properties to the constructor using `this.prop`

Within a React class component, I have multiple methods and the component receives various props. I am contemplating whether I should assign each prop as this.propName in the constructor and then access them using this.propName. For your reference, below ...

Changing the background color of the dropdown button in Vue Bootstrap: A step-by-step guide

I've been struggling to modify the background color of a dropdown button, but no method seems to work. I've attempted changing it by using ID, removing its class and applying a new one, and even using !important to override the styles, but the ba ...

The React Apexchart fails to correctly adjust its height based on its parent container when set to 100%

Currently, I am working with react-apexcharts and facing an issue where I am trying to set the height of the chart to be 100% of its parent element. However, instead of taking the height from its parent, it is only showing a minimum height of 445px. Even a ...