Using Jquery to bind events for selecting focus in and out

There seems to be an issue with binding jQuery events to a select element. The desired behavior is for the .focus class to be added when the select is clicked. However, the logic breaks when an option is selected from the dropdown.

See it in action here: JSFIDDLE

Follow these steps:

  1. Click on the select
  2. Select an option
  3. Click on the select again - .focus not added

Here's the code snippet:

<a>
   <select>
      <option>A</option>
      <option>B</option>
      <option>C</option>
   </select>
</a>​

$('select').focusin(function(){
    $(this).parent('a').addClass('focus');
});
$('select').bind('focusout change',function(){
    $(this).parent('a').removeClass('focus');
});​

Answer №1

The main issue lies in the fact that you're only applying the class when the select is focused, and then removing it when the select's value changes. The problem arises because the select never loses focus when an option is chosen. To solve this and achieve the desired behavior, you can try the following approach:

$('select').click(function(){
   $(this).parent('a').toggleClass('focus'); 
});

$('select').blur(function() {
   $(this).parent('a').removeClass('focus'); 
});

Update - It seems like you want to maintain the feature of removing the class when an option is selected, which is why I recommend binding to click events instead of focusing and blurring.

Answer №2

When you choose an option from a dropdown menu, the focus is shifted away from the select element. This triggers a 'focusout' event on the select, causing the removal of a class from its parent element.

The reason why the class is not added is because the select element is already in focus. To resolve this issue, consider using the '.blur()' and '.focus()' events instead.

For a working demonstration, you can visit: CHECK DEMO

Answer №3

It seems like what you're searching for is a solution similar to this, although there may be room for error:

$('select').on("focus", function(){
    $(this).parent('a').addClass('focus');
});
$('select').on('blur',function(){
    $(this).parent('a').removeClass('focus');
});​

Utilize the on method to attach events and employ the focus and blur events for your select box. Assuming I comprehended your query correctly, this code should address your concern.

DEMO

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

Tips for transforming the appearance of an asp.net page with asp:Content into a stylish css-page

Currently facing an issue where I am unable to change the background-color in my CSS file. As a workaround, I have placed the style directly within an ASP page. <asp:Content Id="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> ...

Determining if a checkbox is checked through a click event

Is the checkbox checked when clicked? $('body').on('click','.beach_access,.parks,.neighborhood_parks',function(e){ if($(this).is(":checked")){ alert("The checkbox is checked."); } ...

Automatically determining the optimal quality from various sources tailored to the individual user - jwplayer

Check out the code snippet below: var playerInstance = jwplayer("mySingleVideoWrapper").setup({ image: getCurrentPosterSrc, sources: [ { file: 'file-360.mp4', label: "360p" ...

The method item.appendChild does not exist as a function

Despite being a common error, I've researched extensively and still can't figure out why it's happening. It seems like it should be an easy fix, but I'm struggling to find the solution on my own. var item = document.createElement("div" ...

What is the process for setting an object's property as a href in an AJAX call?

I've got a quick query. How can I assign an object's property to the href attribute? I've indicated the line with a comment. success: function (listOfTags) { let tagData = ''; $.each(listOfTags, function (i, tag) { ...

"Implementing a seamless auto-refresh feature using jQuery without any

I am working with two PHP files where I fetch data from a database in one file and then retrieve all that JSON encoded data in another PHP file using the .getJSON() method. My goal is to refresh the entire page without any blinking or flickering. Any sug ...

Ways to constrain checkbox choices to only one within an HTML file as the checklist with the checkboxes is being created by JavaScript

I am working on developing an HTML dialogue box to serve as a settings page for my program. Within this settings page, users can create a list of salespeople that can be later selected from a drop-down menu. My current objective is to incorporate a checkbo ...

Height that is determined in real-time

I am attempting to adjust the height of a div based on the size of the screen. Within this div, there is a calendar that contains multiple lines of content, which can be displayed or hidden based on user preference. The height of the calendar is not fixed, ...

Patience is key when waiting for the outcome of an async Javascript function in order to obtain a result (Could it be

Hey there, I've been searching for a solution to my problem even though it's been discussed before. I'm trying to achieve something simple: creating a string like distance is : " + CalculateDistance(position);. The desired result should look ...

jQuery seems to have difficulty selecting the text of a hyperlink's element using the text() or html() methods

I have a <a href=#>Title</a> link and it's the content in between <a href="#"> attribute that I am trying to target but haven't been successful using either the text() or html() jQuery functions. The text() method is returning ...

Efficiently processing multiple Ajax requests with a single callback function

I am currently facing a situation where I need to make multiple AJAX requests and only proceed if all of them are successful. The typical usage of $.when($.ajax(), [...]).then(function(results){},[...]); doesn't quite fit my needs because the number o ...

The true meaning of CSS3 transition is often misconstr

I'm trying to create a simple linear transition effect, but for some reason it's not working. Any suggestions on what might be causing the issue? HTML <div class="button-modern" style="background-color:#e73032"> <span style="color: ...

Creating a navigation bar in React using react-scroll

Is anyone able to assist me with resolving the issue I am facing similar to what was discussed in React bootstrap navbar collapse not working? The problem is that although everything seems to be functioning properly, the navbar does not collapse when cli ...

Move the aircraft across the display in a lively animation

I need help creating an animation where a plane flies across the screen, exits from the left side, and re-enters from the right side in a continuous loop. How can I achieve this effect to make the plane fly endlessly across the screen? Here is my code: ...

Is there a way to update an image from the camera in the background without having to refresh the entire

Utilizing a PHP script (currentimage.php) to obtain a snapshot from my CCTV IP camera has been successful: <?php while (@ob_end_clean()); header('Content-type: image/jpeg'); // create curl resource $ch = curl_init(); curl_setopt($ch, ...

Utilizing gradient effects on table backgrounds with html/css

Trying to enhance my responsive table by adding a gradient background, but encountering an issue where the style being applied is repeating in every cell, creating a messy look. Here's the gradient I'm using: background: linear-gradient(to right ...

The size of the search input and textarea in HTML decreases when viewed on an iPad device

Currently utilizing Bootstrap 3 and AngularJs for this project. Implementing the following markup for the input field with type 'search': <input type="search" class="form-control" id='roomSearch' placeholder="Search" ng-model=&apo ...

When hovering over slick text, it becomes hidden because of non-responsive CSS. Are there any solutions to make it responsive?

I can't seem to get the on-hover dates to appear, even though they are rendered when inspecting the page. I suspect it could be related to a responsive CSS issue or class breaking. How can I resolve this? https://i.stack.imgur.com/jyEJb.png https:// ...

Searching for text within an HTML document using Selenium in Python can be easily achieved by using the appropriate methods and

Is there a way to find and retrieve specific texts within an HTML file using Selenium in Python, especially if the text is not enclosed within an element? <div class="datagrid row"> ==$0 <h2 class="bottom-border block">Accepted Shipment</h ...

angular-ui-tab-scroll: Odd spacing between blocks and tabs, each separated individually

Greetings! I would like to express my gratitude for this wonderful library! However, I am encountering an unusual issue when trying to wrap a tabset with tabs that are included separately. This can be done either by adding individual tab elements manually ...