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

Limited functionality: MVC 5, Ajax, and Jquery script runs once

<script> $(function () { var ajaxSubmit = function () { var $form = $(this); var settings = { data: $(this).serialize(), url: $(this).attr("action"), type: $(this).attr("method") }; ...

Disabling Navigation with Arrow Keys in Prettyphoto

Is there a way to prevent arrow keys from functioning in PrettyPhoto for a specific instance? I have tried using keyboard_shortcuts:false, but it still reloads the frame if left or right arrow keys are pressed, causing the form inside to reset. However, co ...

The drop-down menu does not maintain its selected option after the window is refreshed

I am struggling with a dropdown list as shown below: <select class="span2" id ="sort" name= "order_by"> <option >Default</option> <option >Price</option> <option >Color</option> ...

Creating a visible block in ReactJS: Step-by-step guide

Hello and thank you for all the hard work you do on this platform. I am relatively new to working with ReactJS and have been encountering some difficulties trying to integrate it with sandbox environments like JSFiddle. I have a div element named "app-con ...

What is the best way to display a PDF in a web browser using a JavaScript byte array?

I have a controller that sends the response Entity as a byte array in PDF form to an ajax call. However, I am struggling to display it in the browser despite trying various suggestions from old Stack Overflow questions. Here is the response from the Sprin ...

Ways to reduce the size of the border on the bottom in HTML/CSS

Currently, I am working with a div container (utilizing bootstrap.min.css) that contains another class called divborder. The length of the border-bottom in divborder is quite long and I'm wondering how I can adjust it to be shorter. Below is a snippe ...

Center the radio buttons regardless of the length of the text

My dilemma lies with 3 radio buttons and their corresponding labels - while 2 of them are aligned perfectly beneath each other due to their matching character lengths, the middle one extends further making it look misaligned. Check out this fiddle. Below ...

Leveraging the jQuery live() function to optimize heavy usage of Ajax on a website

Trying to ensure that all scripts are properly executed as content is loaded and removed from the page using jQuery load has been a challenge. The most effective approach so far has been the live function, but I have encountered difficulties in getting it ...

tips on adjusting images to the size of the screen without them being on html files

I understand that sharing links may not be appropriate for this forum, but I'm unsure how else to seek assistance. My apologies for any inconvenience. I am currently working on a website for a doctor, and the image you see is of a patient. I'm ...

The button fails to function properly following the initial successful loading of ajax data

var Update = { init: function(){ $('.find').on('click', function(e){ e.preventDefault(); var $this = $(this), $form = $('#searchForm'); BLC.ajax({ ...

Initiate the python script on the client's end

Currently, I am in the process of initiating a Python script designed to parse a CSV file that has been uploaded by the user through the UI. On the client side, how can I effectively trigger the Python script (I have explored using AJAX HTTP requests)? Add ...

Instant data entry upon clicking

In an attempt to automate input based on image pairs, I encountered a challenge. On one side, there are two images that need to be matched with input fields, and on the other side, there are corresponding letters for each image to fill in the inputs upon c ...

Enhancing JQuery Autocomplete with Hover Highlight and Widthadjustment

Currently, I have implemented a jquery autocomplete feature for an address textbox. As the user types in their address, the textbox successfully retrieves and displays matching addresses. The width of the autocomplete dropdown is dynamically set to the w ...

How can I retrieve the file name and any other requested parameters in the serveResource method using an ajax call?

I'm currently utilizing ajax to submit the data on my jsp page in a liferay custom portlet without needing to refresh the entire page. Unfortunately, I've encountered two issues with this approach: Although the Ajax function successfully pas ...

What is the technique for determining the scale percentage of an image with the background-size property set to cover?

I am trying to determine the scale of an image after it has been resized. By using background-size: cover on the body background image, I want to ensure that the image maintains its aspect ratio and expands or shrinks to fit both the width and height of t ...

What is the best way to display only li elements that possess a specific class utilizing javascript / jquery?

I have a bunch of li's: <ul> <li class="one"></li> <li class="one"></li> <li class="two"></li> </ul> and I want to display only the ones with the class "one" I attempted something like thi ...

Having a problem with the hover effect on the navbar component

Whenever I hover over the individual links, I notice that the color change doesn't extend all the way up. I have a feeling there is a more efficient way to achieve this than my current approach. Any assistance would be greatly appreciated! HTML: < ...

Alignment issue detected

I was attempting to center these 4 divs inside a container both horizontally and vertically, but they are stuck at the top edge of the <div>. They aren't moving down and remain fixed at the top. /* Footer */ #footer { width: 100%; hei ...

How can I reset a CSS position sticky element using JavaScript?

I have created a page where each section fills the entire screen and is styled using CSS position: sticky; to create a cool layered effect. Check it out here: https://codesandbox.io/s/ecstatic-khayyam-cgql1?fontsize=14&hidenavigation=1&theme=dark ...

What could be causing the absence of a background image in CSS?

When I try to view my local desktop file, the CSS background image isn't showing up. Here's the code I'm using: <!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <link rel="stylesheet" text="type/css" href="dis ...