Connect the CSS active state to a JavaScript event

.el:active{
    background:red;
}

Is there a way to associate the above CSS active state with a JavaScript event, like this:

$('.el').on('active', function(){  
    img.show();
});

I want the image to remain visible when el is pressed and hide when it's released.

Answer №1

To make an image appear when clicking a button and disappear when releasing it, you can utilize the `onmouseup` and `onmousedown` events. Take a look at the code snippet below.

function mouseDown() { 
  document.getElementById("imageId").style.display = "block";
}

function mouseUp() {
  document.getElementById("imageId").style.display = "none";
}
img{
  display:none;
}
<button onmousedown="mouseDown()" onmouseup="mouseUp()">Click me</button>
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPwAAAC0CAMAAACHfrFUAAAAM1BMVEX///8AAABmZmbU1NSjo6P19fXf39+GhoYjIyO8vLxTU1Pq6uqVlZWwsLB3d3c9PT3IyMgBwMchAAAHeElEQVR4nO2d6ZbqKhCFNYMZHOL7P+29Lk8M1LApCN3arto/OxTwCaliCn04uFwul8vlcrlcLpfL5XK5XC6Xy+VyuVwul8vlcrlcLpfL5XK5XC6Xy+VyuVwul+svq33qdws9tWmdf7oOl/m4ahnuBTk0R1HNcD0VmEXqcFpjnlqrtjT52PWV4B9aLjp/BXhW1SUDvr8JScfc1scUjYZfAZ5RGZM9dBrlxENe46coLnJ2FeAnCmSHn9Qy5yz6JMUsNn4F+I5k2Zrh76i6OfRpilGirwB/I1l2cjIOr/X5p5qq8CJ9BXhay4ucjMH3s5xw1aUq/HHkEbsCPI11Vr+o/EjAYhe88CLVgCeZKp2Zoih+MdBSF553pRrwBMuWylLytS78kb72NeDjWKc4ewqvJQs1Wj2+EZ56pxrwcazT4leLC57vfcviBB1CWOH/p2wnYaCZqMOx42q1tP8Uxzol0pGC6Rv/9EZ00GN96wV4sSYNNuPTFJBWzFIarHP4gTw9ycZGhy/DC/HkBM1K4I+mVDEHCQnr70c7xLALnk+xBmhWBB/5JS1RBE8dw8uvk+qO++DZ3GGEZkXwIVdvgld6PX9gm9xq8Lzp78isCD50ymoIi+DpQOj14Eoe2Pq9C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r+8W74WX3X2XgOfjWwRv+aAWwCPAnfCiu28T8HnHTy3fFQJ4eiR0BmaZ8KK7P6fgUaGsm1o+JgbwNLsBmGXCi+5eLjWAZz8Z+ADA9HmVDs/8ywTMMuEld98k4dnnZ6BXWA5dA3gWOc/ALBNecvdDEp79ZOAsvuW4PYCnnWxBZpnwkrvvkvDo+zFkVgBP/d0FmeXCC+6+TVNQq615WVeysOvwLLsTMsuFF9z9OQ1PP0bZXDB9I0yvvA5PHfICzXLhBXd/SMPTAe4WfGl+tjtDVHjqQS7QLBdeX4pF8Ozh6wEN87a7+DR41jRnaJYLz9392oUhPGV8LVWRpjJ9T6nCs+NwDTbLhddXhiE8Db/rL6beqFAC37JP2FK3peTCswzWAmDBPa3XWc7NeFGOAN9OPBDR2TFLIVwV000Anrn79bWC8MzseVVM2b0J6Y12sQpGMymmaz7lNTfHJbPXcbkKbWW9etQGX3Q3FoRXb4CgmaTeN73cSvBL0a1oEJ66+9fPSzMpuBvLfOesiYJ/jr0bnkJelb+zF067SWmT/TZAC4Vw/8R+eJLDi5FmQuHP8BLIo9RN98BLd2/shyd++1VjmgmbnqmXymgGe+DFe0f2w8fufluITbOALxCPGTcBGiiUW4T3w9OTOXZ4eAOoNcRbKBrFc+6Hj9395qTS8Ig+ix1TNOr7sx8+przKf5bhD73W83P6PKQYB+A6KsBHf9aPIMiVmCSfL1/OnA3f3PAN7zXgo9bbwpMN/tB3FH+x3ny5id3Sb/v1LJf7G7MqVT/dNv4ZXEf/rerb9tpNv/1vHVwul8vlcrlcLpfL5XK5XC6Xy+VyuVz79B9OlkuANHOGHgAAAABJRU5ErkJggg==" id="imageId" alt="">

Answer №2

Implement a mechanism that triggers with the keydown and mousedown events to initiate, and concludes with the keyup and mouseup events.

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

Notify when a certain element's ID is visible on the screen using the jQuery appear method

Having trouble getting this plugin to cooperate: https://github.com/morr/jquery.appear I attempted to reference the plugin from a CDN using Ajax: http://cdnjs.cloudflare.com/ajax/libs/jquery.appear/0.3.3/jquery.appear.js Why isn't it working as expe ...

Unable to convert data to a JSON string

I've created a tool for building dynamic tables: <div class="container"> <div class="row"> <div class="col"> <hr> <h3>Add your data</h3> <button id="addTd" type="button" class="btn btn-pr ...

What is the best way to implement an anchor link in my JavaScript code?

I'm struggling to wrap my head around this, as my thoughts seem to have vanished. On my webpage, there's a button element with an id: for example <button id="someId"></button> Within the document.ready function, I've set up an ...

Creating new form fields dynamically using JavaScript (triggered by onClick event)

I want to dynamically add fields based on user interaction. For instance, when the checkbox or radio button is clicked, additional fields like buttons and textfields should appear. Is it possible to achieve this using onClick? If so, can you please provide ...

Improprove the performance of an array of objects using JavaScript

Hello there, I am currently in the process of creating an array. this.data = [{ label: 'Total', count: details.request.length, }, { label: 'In-Progress', count: details.request.filter((obj) => obj.statusId === 0 || ob ...

404 Error: JSON POST and GET Request Not Located

I need assistance with setting up an API in Django as I am encountering errors in the JavaScript console. The error messages are: GET http://127.0.0.1:8000/edit/undefined 404 (Not Found) POST http://127.0.0.1:8000/edit/undefined 404 (Not Found) Is there a ...

Tips for effectively removing objects from a PixiJS application

I have embarked on a game development project using Pixi.js that involves items falling from the top of the canvas. The functionality I've implemented so far allows items to spawn and move down the canvas until they reach the end of the window, at whi ...

What is the best way to implement a nested lookup in MongoDB within a field?

Within my database, I have a collection named Randomhospital. Inside this collection, there is a field named hospital structured as follows: { "id": "GuDMUPb9gq", "Hospital Name": "UPHI", "Hospital City&qu ...

Having trouble getting Bootstrap 5 to work with a position-relative row?

I am having trouble placing the * sign on the left side. Whenever I try to do so, it only works if I remove the row class. <!doctype html> <html lang="fa" dir="rtl"> <head> <meta charset="utf-8"> ...

Tips on adjusting a standard CSS layout with JavaScript and jQuery to generate a unique ID for the updated style

My CSS contains IDs that look like this: <style> .HIDE-DISPLAY-k { background-color: orange; position: fixed; width: 100%; height: 100%; top: 10px; bottom: 0px; left: 10px; right: 0px; overflow: hidden; } #SHOW- ...

Achieving second class using jQuery from a choice of two

Looking for assistance with retrieving the second class from an element that has two different classes. I attempted to use the split method but encountered some issues, can anyone provide guidance? js_kp_main_list.find('li#kp_r_04').addClass(&ap ...

implementing AJAX functionality in Laravel when a drop-down item is selected

Hello there, I am a newcomer to the world of coding and I'm currently learning Laravel for a personal project. My goal is to retrieve data from a database based on the selection made in a dropdown menu. Here's the code for the dropdown menu: < ...

Increase the quantity with animation

I am attempting to increment a number within an element on the page. However, I require the number to have a comma included while the increment should only increase by 1 digit every second. The code is currently functional, but I am facing a dilemma regar ...

Is it possible for the `position: fixed` property to interfere with mix-blend-mode, and if so, are there

Struggling to make box-shadows cooperate with different backgrounds? The traditional method involves using mix-blend-mode and adding a pseudo element behind the main one for the effect. You can see an example of this technique here (click the + icon in th ...

Column Flow in CSS Grid: Maximizing Auto-Fit - How to Optimize Row Layouts?

Having some trouble understanding how auto-fill and fit work in grid layouts. I am familiar with basic CSS, but new to working with grid layouts. I have a set of checkbox items with labels that I want to display in columns depending on screen size, with c ...

Is there a way to eliminate get variables and filename from a URL using JavaScript or jQuery?

I've been researching this issue, but unfortunately, I haven't been able to find a definitive solution for my specific needs. Let's say I have a URL like... How can I extract this URL and remove the "index.php?search=my+search" part so that ...

What is the most effective method for testing event emitters?

Imagine I have a basic component structured like this: @Component({ selector: 'my-test', template: '<div></div>' }) export class test { @Output selected: EventEmitter<string> = new EventEmitter<string>() ...

JavaScript is unable to make changes to the page once it has finished loading

I have implemented a JavaScript code that allows me to send messages in a chat interface: function sendMessageToChat(conversation, message) { $("#content").html(conversation + message); $(".current-msg").hide(); $(".current-msg").delay(500).fadeIn ...

What is causing the CSS transition to fail in the updated DOM?

When attempting to apply a CSS transition as shown in the following code snippet: https://jsfiddle.net/sunyuu/e58sfeva/17/ var Main = { data () { return { isActive: false, childStyle: {} }; }, methods: { sho ...

steps to iterate through an array or object in javascript

Hello, I am facing an issue while trying to loop through an array or object. Can someone help me out? Are arrays and objects different when it comes to using foreach? function fetchData() { fetch("https://covid-193.p.rapidapi.com/statistics", { ...