What is the best way to add a CSS rule to JavaScript?

animation: scaleUp 0.3s linear 0.4s forwards;

animation: scaleDown 0.3s linear forwards;

Greetings! I'm currently working on adding animations to my content filtering functionality. Specifically, I want to incorporate the aforementioned CSS rules into the JavaScript code below in order to hide and show elements based on their class. However, I am unsure about how to properly structure the tags due to my limited knowledge of JavaScript. Any assistance with this matter would be greatly appreciated. Thank you.

$(document).ready(function() {
$('#filterOptions li a').click(function() {
    // Get the class attribute of the clicked item
    var ourClass = $(this).attr('class');

    // Remove active class from all buttons
    $('#filterOptions li').removeClass('active');
    // Add active state to clicked button
    $(this).parent().addClass('active');

    if(ourClass == 'all') {
        // Display all items
        $('#ourHolder').children('div.item').show();    
    }
    else {
        // Hide elements that do not share ourClass
        $('#ourHolder').children('div:not(.' + ourClass + ')').hide();

        // Show elements that share ourClass
        $('#ourHolder').children('div.' + ourClass).show();
    }
    return false;
});

});

Answer №1

As far as I can tell, there seems to be no reason why the solution below wouldn't function:

$("#myContainer").css("animation","expand 0.3s ease-in-out 0.4s forwards");

or

$("#myContainer").css({"animation" : "expand 0.3s ease-in-out 0.4s forwards"});

However, it is considered best practice to define this CSS in a class and then switch between classes.

Just a heads up, the selector used here is #myContainer, which is just an example and may need to be adjusted based on your specific needs.

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

Retrieve all direct message channels in Discord using DiscordJS

I need to retrieve all communication channels and messages sent by a bot. The goal is to access all available channels, including direct message (DM) channels. However, the current method seems to only fetch guild channels. client.channels.cache.entries() ...

Using a Javascript plugin in Laravel with Vue by importing it into the project

Currently, I am in the process of creating a Vue component by utilizing the functionalities provided by the JavaScript plugin known as Cropper JS. The application is developed using Laravel 5.6. Initially, I installed Cropper JS via NPM: npm install cropp ...

efficiency of a process during ng-repeat execution

Do you see a distinction in how ng-repeat is written in these two examples? <div ng-repeat="item in getItems()"> Versus this: <div ng-repeat="item in items"> Imagine getItems is structured like this: $scope.getItems = function() { return ...

Changing letter cases in a textbox using Javascript

I have a challenge to create a code that can switch the case of text entered by the user. Here is what I currently have: var num; function toggleTextCase(str) { return str.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase( ...

Obtain specific information from custom fields on the product page

What am I trying to achieve? I want to create a single product page that displays custom fields which need to be filled out before the item can be added to the cart. Additionally, I have implemented a button that should take all the values entered in the ...

ES6 Set enables the storage of multiple occurrences of arrays and objects within

Review the script below. I'm currently testing it on Chrome. /*create a new set*/ var items = new Set() /*add an array by declaring its type as an array*/ var arr = [1,2,3,4]; items.add(arr); /*display items*/ console.log(items); // Set {[1, 2, 3, ...

What is the reason for the value of an object's key becoming undefined when it is set within a loop?

I've always wondered why setting a certain object's key as its own value in a loop results in undefined. Take this code block, for example: var text = 'this is my example text', obj = {}, words = text.split(' '); for (i = ...

Is there a way to transform a regular CommonJS declaration into an ECMAScript import when it is making multiple requires in a single line?

As a beginner in JavaScript, I am interested in converting this line into an import statement: var sass = require('gulp-sass')(require('sass')); I have successfully converted the other requires into imports but I'm struggling wit ...

Tips for maintaining a user's session post-login with Passport and Express JS

I recently set up a node backend using express and integrated Passport for authentication purposes. My application has a route called /login for logging in and another route called /me to retrieve information about the currently logged in user. Below is t ...

Tips for inserting a row component into a table using Angular 7

I am currently using the latest version of Angular (7.2.0). I have created a custom tr component as follows: import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-table-row', templateUrl: './table- ...

Modify text using JQuery when the span is clicked

Currently, I am attempting to retrieve a value from the database: SenderDriver->total_trips. Everything seems fine, but I have a specific id that needs to be placed within onClick(), which then sets the value of the database variable: SenderDriver-> ...

A comprehensive guide on personalizing Bootstrap 4 tooltips to suit your specific needs

I would like to customize the tooltip in Bootstrap 4 based on the screenshot provided below: https://i.stack.imgur.com/wg4Wu.jpg <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta chars ...

What steps can be taken to resolve the error ERROR TypeError: undefined is not an object when evaluating 'userData.username'?

.I need help fixing this error ERROR TypeError: undefined is not an object (evaluating 'userData.username') Currently, I am working on a small application where users are required to allow permission for their location in order to save their cit ...

Why is it that the condition of being undefined or not functioning properly in state?

I am currently facing an issue with a piece of code I wrote in React JS. The state variable is not functioning as expected and even after modifying it upon button click, nothing seems to be working. After checking the console, I noticed that the state rema ...

Sorting data by percentages in AngularJS

I am currently facing an issue with sorting percentages in a table column. Despite using methods like parseFloat and other AngularJS (1.5.0) sorting techniques, the percentages are not being sorted as expected. [ {percentage: 8.82} {percentage: 0. ...

Error detected in JSON syntax... Where is it hiding?

After running the code through jsonlint, it flagged an error on line 17. However, upon close inspection of the file which contains about 1000 lines, I couldn't pinpoint the issue. It's possible that the problem lies further down the file, but I w ...

Incorporate a widget with dynamic height adjustment

We are currently working on creating a widget that can be easily embedded by third-party websites. Our goal is to have the widget automatically adjust its height through the embed script. Initially, we considered using an IFrame generated by our JavaScrip ...

Update the image within the svg tag

I am attempting to modify a preexisting SVG element within an HTML document. Here is the current code: <svg class="logo" viewBox="0 0 435 67"> <!-- IMAGE DIMENSIONS --> <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#logo- ...

What is the most efficient way to retrieve the key at a specific index within a JavaScript map object?

If I have the map object shown below: const items = new Map([['item1','A'], ['item2','B'], ['item3', 'C']]) I am trying to retrieve the key at index 2. Is there a method other than using a for ...

Vue.js2 - Detection of Observer in Array

A question for beginners in vue.js. I am trying to display data using the CanvasJS Library that is received via websocket. Everything works fine with the data until I introduce vue components into the mix. Let me clarify: export default { data() { r ...