What is the best way to ensure a JavaScript event is only activated after another event has been triggered on the same element?

I have set up a mouseleave event for the select tag. However, I want this event to only happen when a user clicks on the select tag first and then moves their mouse away from it.

function loseFocus() {
    var dateSelect=document.querySelector('[name="dayCount"]');
    dateSelect.blur();
    console.log('mouse leave event triggered')
}
<select name="dayCount" onmouseleave="loseFocus()">
  <option >op1</option>
  <option >op2</option>
  <option>op3</option>
</select>

Answer №1

To establish a variable as false and trigger a click event on the drop-down menu, simply set up a callback to change that variable to true when the click event occurs. Then, in the blur event callback, include a condition to verify if the variable is indeed set to true.

If you prefer not having to click outside of the drop-down menu after making a selection, consider implementing a mouseout event as well.

let dateSelect = document.querySelector('[name="dayCount"]');
let clicked = false;

function changeClick(){
  clicked = true;
}

function checkFocus(){
  clicked === true ? console.log('BLUR FIRED -> select has lost focus') : null;
}

function mouseOut(){
  clicked === true ? console.log('MOUSEOUT FIRED -> Your mouse is not over the select element') : null;
}

dateSelect.addEventListener('click', changeClick);

dateSelect.addEventListener('blur', checkFocus);  
  
dateSelect.addEventListener('mouseout', mouseOut);
<select name="dayCount">
  <option >op1</option>
  <option >op2</option>
  <option>op3</option>
</select>

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

Combining Laravel and VueJs for a Multi-Page Application (MPA)

I have recently developed a website using a combination of Laravel and VueJs. However, I am facing some confusion regarding the most suitable routing architecture to implement. Currently, my application has the following setup: The routing system is man ...

Adjusting color of fixed offcanvas navbar to become transparent while scrolling

After creating a navbar with a transparent background, I am now using JavaScript to attempt changing the navigation bar to a solid color once someone scrolls down. The issue is that when scrolling, the box-shadow at the bottom of the navbar changes inste ...

offspring of offspring in jquery animation remains stationary

I'm experiencing an issue with a jquery animation on containers that are set to 100% width and height. Specifically, the children elements that have position absolute move with the container, but when a child of a child has two instances of position a ...

Click the button to access the login form created using React components

I have been working on developing a login form that includes various input components and a button component. SignIn.js class SignIn extends Component { render() { return ( <article className="br2 ba dark-gray b--black-10 mv4 w-100 w-50-m ...

Revamping the website to become a Progressive Web App

I am in the process of transforming my website into a Progressive Web App (PWA) and have made some updates to my code to facilitate this: index.html <script> if('serviceWorker' in navigator) { navigator.serviceWorker.registe ...

Having trouble with the babel-loader and its version compatibility, as well as not finding the babel-loader folder in the node_modules directory when

Here are the steps I've taken: I cloned the project from Github. Ran the command 'yarn' to start the project. Encountered an error after running the command 'yarn start'. Even after following the steps provided in the e ...

Tips for saving data after reading lines in Node.js

I am working on a project where I need to read data from an external text file into my function. How can I efficiently store each line of the file as a separate variable? const fs = require("fs"); const readline = require("readline"); const firstVariable ...

What is the process for ordering by a many-to-many relationship in Sequelize?

I am dealing with a many-to-many relationship between User and Category, connected through the UserCategory model. Here is the code snippet illustrating this relationship: let user = await User.findAll({ where: { id: req.query.user }, attribut ...

Mastering the Art of Crafting an Effortless Slide Showcase

I have created a carousel that works fine except for one issue: when I reach the last image or go back from the first image, I want the image to be displayed. For example, when you click the right arrow after reaching the last image, it should show the fir ...

Send an array from PHP to jQuery using AJAX, then send the array back from jQuery to PHP

I am facing a dilemma where I am passing an array from PHP to jQuery AJAX using `json_encode` and storing it in an empty array declared in the jQuery script as `var myarr = []`. Later in the same script, I am sending the same array `myarr` back to the PHP ...

Using the typeof operator to test a Typescript array being passed as an object

I have a puzzling query about this particular code snippet. It goes like this: export function parseSomething(someList: string[]): string[] { someList.forEach((someField: string) => { console.log(typeof someField) }) Despite passing a s ...

Comparison of WebAPI Response Codes: Understanding the Difference Between 401 and

As a part of my learning project, I am developing a WebAPI and striving to implement best practices. The initial focus is on creating an authentication API that accepts an authentication object in JSON format: { username: myusername, password: mypa ...

Conquering cross-origin resource sharing (CORS) using XMLHttpRequest without relying on JSONP

Appreciate your time in reading this inquiry! For the past few days, I've been grappling with an AJAX request issue. Despite scouring through numerous answers on Stack Overflow, I'm still unable to find a resolution. Any assistance would be grea ...

Owner executes the Snowflake Store Procedure

Attempting to create a stored procedure with 'execute as owner' in order to return a list of tables. The SP was successfully created, however calling it results in an error. create database garbage; CREATE OR REPLACE procedure garbage.public.san ...

Issues with Node.js and Socket.io: Receiving error "Cannot read property 'on' of undefined"

I've encountered an issue while trying to establish a websocket connection using socket.io and node.js. Here is the setup I'm working with: Operating System: Windows 7 Node version: 6.9.2 NPM version: 4.0.5 Packages: "express": "^4.14.0" "soc ...

Steps for downloading a file attached to a gridview

It seems like I'm overlooking something quite straightforward. I am creating binary files that I am associating with a GridView. FileDownloadGrid.DataSource = downloadList; FileDownloadGrid.DataBind(); The part of the grid that interests me ...

Using a promise inside an Angular custom filter

I am attempting to implement a filter that will provide either a success or error response from the ret() function. The current code is returning {}, which I believe is its promise. .filter('postcode', ['$cordovaSQLite', '$q' ...

Set a Value to a Specific Node in a Multidimensional Array Using JavaScript

Trying to update an element within a JSON object with a new value (text/object/array). I have a swap function that takes in the JSON object, an array with indexes to retrieve the element, and the value to replace it with. Currently using eval, which some c ...

I am encountering a situation where the model.findOne() method in my Node.js application is unexpectedly returning null, despite the

My goal is to verify if the user already exists in the database. I have set up a system where, on the client side, I use a JavaScript function to send the user's email ID to a Node.js route. This route then checks if the user exists in the database or ...

Help me figure out how to independently toggle submenus on my navbar by utilizing the Vue.js composition API

I am currently working on developing a navbar using the Vue.js composition API. My primary objective is to toggle the submenus when a user clicks on them. However, since I am iterating through an object to display the submenus, I am faced with the challeng ...