What is the best way to make an input text the focus when an item on a dropdown menu is clicked?

I have a website with a dropdown menu and an input box. I want the user experience to be more seamless by automatically focusing the mouse cursor inside the input box when they click on an option in the dropdown menu. This way, users can start typing right away without needing to click into the input box each time.

Is there a way to achieve this functionality?

Here is the Jsfiddle link: http://jsfiddle.net/mlynn/jyrbepyz/3/

Thank you.

HTML

<section id="heady">
    <div style="text-align: left;padding:25px 70px;display:inline-block;float:left;"><b><a href="index.html">Site</b></a></p></div>

    <div style="text-align: right;padding:25px 70px;display:inline-block;float:right;">    
            <a href="index.html">Home</a> | 
            <a href="index.html">Generic</a> |
            <a href="index.html">Elements</a> |
            <a href="index.html">Sign Up</a>
    </div>
</section>
<section id="wrapper">
    <br><br>
    <img src="images/blacksquare.png" width="525" height="197"></img>

    <br><br><br>
    <div>
        <div style="vertical-align:top;display:inline-block;float:left;">        
            <ul class="navbar cf">
                <!-- <li><a href="#">item 2</a></li> -->
                <li style="width:200px;">
                    <a href="#" class="ActiveListItem">#</a>
                    <ul>
                        <li><a href="#">1</a></li>
                        <li><a href="#">2</a></li>
                        <li><a href="#">3</a></li>
                        <li><a href="#">4</a></li>
                        <li><a href="#">5</a></li>
                        <li><a href="#">6</a></li>
                        <li><a href="#">7</a></li>
                    </ul>
                </li>
            </ul>
        </div>                                                               
        <div class="container lister" style="display:inline-block;float:left;vertical-align:top;padding:0px 0px 0px 10px;">
            <form action="">
                <input type="text" id="todo" placeholder="Enter a To-do and hit enter">
            </form>
            <br>
            <!-- <ul class="active">
                <li>Work <a href="">X</a></li>
                <li>Sleep <a href="">X</a></li>
                <li>Repeat <a href="">X</a></li>
            </ul> -->
        </div>
        <div class="container lister" style="display:inline-block;float:left;vertical-align:top;padding:0px 0px 0px 10px;">
            <ul class="active">
                <li>Work <a href="">X</a></li>
                <li>Sleep <a href="">X</a></li>
                <li>Repeat <a href="">X</a></li>
            </ul>
        </div>
    </div>             
    <div class="Category1">
        <!--list items that user assigned "1" from dropdown menu would be placed in this div-->
    </div>

    <div class="Category2">
    </div>
    <div class="Category3">
    </div>
    <div class="Category4">
    </div>
    <div class="Category5">
    </div>  
    <div class="Category6">
    </div>  
    <div class="Category7">
    </div> 
</section>

<section id="feety">
I think, therefore I am
</section>

CSS

/* Theme */

@import url(http://fonts.googleapis.com/css?family=Open+Sans:400, 300, 600);


 * {
    padding:0;
    margin:0;
}


html {
 background:teal;
}


body {
}

a {
    color: #D9D9D9;
    text-decoration: none;
}
a:active, a:hover {
    text-decoration: underline;
}



#heady {
    text-align: center;
    width:100%;
    height:75px;
    background-color:#222;                      
    font-family: Tahoma;
    font-size: 16px;
    color:white;
    position:relative; 
}

#wrapper {
    text-align: center;
    width:1000px;
    height:1000px;
    margin-left:auto;
    margin-right:auto;
    background-color:teal;                       
    font-family: Tahoma;
    font-size: 16px;
    position:relative; 
}


#feety {
    text-align: center;
    width:100%;
    height:100px;
    background-color:darkslateblue;                       
    font-family: Tahoma;
    font-size: 16px;
    color:white;
    position:relative; 
}





.Category1 {
    background:blue;
}


.Category2 {
    background:green;
}

.Category3 {
    background:yellow;
}

.Category4 {
    background:orange;
}

.Category5 {
    background:purple;
}

.Category6 {
    background:gold;
}

.Category7 {
    background:maroon;
}

/* clearfix */
/**
 * For modern browsers
 */
.cf:before,
.cf:after {
    content: " "; 
    display: table; 
}

.cf:after {
    clear: both;
}

.cf {
   * zoom: 1;
}


ul.navbar {

  background:white; 
  border-style:solid;
  border-color:gray;
  border-width:1px;
  width: 200px;
  border-radius: 4px;

}


.ActiveListItem:after {
    content: "\25BC\00a0\00a0";                        
    float:right;
    font-weight:900;
    padding: 0px 0px;
    font-size:100%; 
    line-height:20px;             
}




ul.navbar li a.ActiveListItem {
    background:white !important;
    color:black;
    border-style:solid;
    border-color:white;
    border-radius:4px;
    padding:3px 5px !important;
    font-weight:normal !important;
    margin-left:14px;
    margin-

right:0px;

}

ul.navbar li {
    position: relative;
}

ul.navbar li a {
    display: block;
    color: white;
    padding:10px 5px;
    text-decoration:none;
    transition: all .2s ease-in;

}

ul.navbar li a:hover,
ul.navbar li:hover > a {
    background:#a6d0e1; 
    color: #333;
    font-weight:900;

}

    ul.navbar li ul {
        margin-top: 1px;
        position: absolute;
        background: #222;
        font-size: 14px;
        min-width: 200px;
        display: none;
        z-index: 99;
        box-shadow: inset 0 2px 3px rgba(0,0,0,.6),
        0 5px 10px rgba(0,0,0,.6);
    }

ol, ul { list-style: outside none none; }

.hidden { display: none; }


.container {
    width: 60%;
    margin: 0px auto;
}

form {}

input,
ul {
    background: #eee;
    border-radius: 5px;
    width: 100%;
    box-sizing: border-box;
    font-family:"Tahoma";
}

input {
    padding: 10px 10px 10px 20px;
    border: 1px solid #ccc;
}

.lister ul {
    list-style: square inside;
    padding: 10px;
}

.active { border: 1px solid #ccc; }
.inactive { display: none; }

.lister li {
    padding: 10px;
    font-weight: 600;
    color: #34495e;
}

.lister li:nth-child(odd) {
    background: #dadfe1;
    border-radius: 5px;
}

.lister li > a {
    float: right;
    text-decoration: none;
    color: #22313f;
    font-weight: bold;
    transition: all .2s ease-in-out;
}

.lister li > a:hover {
    font-size: 110%;
    color: #c0392b;
}


.lister li:before {
    content: "#";                   
    float:left;
    font-weight:900;
    padding: 0px 0px;
    font-size:100%; 
    line-height:20px;            
}

JS

// sub menus identification
$(function() {

    $('.navbar ul li a').click(function(){  
        $('.navbar > li:first-child > a').text($(this).text());
        $('.navbar > li > ul').addClass('hidden');
        $('.navbar li ul').slideToggle(100);
    });

    $('.navbar > li').mouseenter(function(){
        $(this).find('ul').removeClass('hidden');
    });

    $('.ActiveListItem').click(function(){        
        $('.navbar li ul').slideToggle(300);
    });    
});
    //newList
$(document).ready(function() {

    var ul = $('.lister ul'),
        input = $('input');

    input.focus();  

    $('form').submit(function () {
        if (input.val() !== '') {
            var inputVal = input.val(),
                activeNumber = $('.ActiveListItem').text();

            if (activeNumber == "1") {
                /*Fantasy code goes here...?*/
            }

            ul.append('<li>' + activeNumber + ' ' +inputVal + '<a href="">X</a></li>');
            if (ul.hasClass('inactive')) {
                ul.removeClass('inactive')
                    .addClass('active');
            }
        };
        input.val('');
        return false;
    });

    ul.on('click', 'a', function (e) {
        e.preventDefault();
        $(this).parent().remove();

        if (ul.children().length == 0) {
            ul.removeClass('active')
                .addClass('inactive');
            input.focus();  
        }
    });
});

Answer №1

Ensure to target the correct elements with your code snippet: var ul = $('.lister ul')

Take a closer look at where the elements .lister and ul are located in your HTML structure

You may want to focus on selecting the appropriate DROPDOWN UL anchors
by using the accurate selector:

$(".navbar.cf li ul li").on("click", "a", function(e){
    e.preventDefault();
    input.focus(); 
});

http://jsfiddle.net/jyrbepyz/5/

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

Is it necessary to encode the content before transmitting HTML in JSON from the server to the client?

When it comes to sending HTML content from the server to the client for displaying user comments in a rich JS app that communicates through a JSON API, there are some considerations to keep in mind. One important question is how to handle the content with ...

Attempting to upload an item using ThreeJs

Can someone assist me with loading an object file from my local browser in Threejs ( Rev 71)? I keep encountering an error that says loadModel.html:1 Uncaught SyntaxError: Unexpected token #. Even after trying to load the object file using chrome --allow- ...

Implement a termination condition for mapping in React

Here is a code snippet to consider: <TableHead> {documents.map((docs, i) => ( <TableRow key={i}> <TableCell> {{docs.name} </TableCell> </TableRow> ))} </TableHead> I am looking for a wa ...

Different from Window.Print()

I am looking to implement a print button that will trigger the printing of the entire webpage when clicked. I have been attempting to achieve this using Window.print() in JavaScript, but I encountered an issue where the link stops working if the print bu ...

Dynamic stylesheet in Vue component

Currently, I am utilizing a Vue component (cli .vue) and facing the challenge of selectively displaying my stylesheet based on a boolean value. To put it simply: When myVar==false, the component should not load its styles. <style v-if="myVar" lang="sc ...

Interactive searching with Smalltalk Seaside and jQuery as you type

renderFilterOn: html |aFilter| html textInput onKeyUp: (html jQuery ajax callback: [:val | aFilter := val] value: ((html jQuery this) value); script: [:s | s add: ((s jQuery class: 'itemnames') ...

developed a regular expression to disregard .goutputstream documents

After successfully creating a watcher with chokidar, I encountered an issue when trying to ignore certain files using regex. I am struggling to figure out what went wrong in my code or regex implementation. Below is the snippet of the code: const watcher ...

Customized link routing / Deep linking

I need some help. I am managing a standard website and I want to redirect custom URLs to specific pages when visitors access the site. For instance: - index.html should point to custom_index.cfm?custom_id=1&page_id=1&inc=index - about.html shou ...

What is the best way to extract and count specific values from a JSON file using JavaScript?

My JSON data looks like this: /api/v1/volumes: [ { "id": "vol1", "status": "UP", "sto": "sto1", "statusTime": 1558525963000, "resources": { "disk": 20000000 }, "used_resources": { "disk": 15000000 }, "las ...

Error: Unexpected error occurred due to the absence of the defined variable `$`

Why is it that everything seems to be working fine in homecooked.js, but the script below it is causing a "ReferenceError: $ is not defined" in the browser? <script src="assets/jquery-1.8.2.min.js" type="text/javascript"></script> <sc ...

The custom element is unfamiliar: Have you properly registered the component? Vue.js in Laravel

I encountered this problem: Unknown custom element - did you register the component correctly? I am trying to implement a like system using Vue.js. Can someone please guide me on how to fix this issue? Despite my best efforts, it seems like everything is i ...

Revamp the bootstrap Tooltip.prototype.fixTitle() override function

Hey there, I have a question regarding the Bootstrap tour that I'm using on my website. I want to customize the following method: Tooltip.prototype.fixTitle = function () { var $e = this.$element; if ($e.attr('title') || typeof ($ ...

Tips for circumventing the use of responsive tables in Buefy

I am facing a challenge with displaying data in a Buefy table in a way that it appears as a conventional table with columns arranged horizontally on all devices, rather than the stacked cards layout on mobile. In order to accommodate the content appropriat ...

Delaying Variable Assignment in Node.js until Callback Function Completes

I am currently working with Node.js, Express, MongoDB, and Mongoose in my project. One specific task involves fetching the largest id number of a document from the MongoDB database and passing it back to the program. To better organize my code, I moved thi ...

Function for editing a button in an AngularJS single page application

I am a beginner in AngularJS and I'm currently working on a project to create a single page application for tracking expenses. However, I'm facing some challenges with my code. Although I have successfully implemented most of the functions, I am ...

Having trouble with vendor CSS not being recognized during brunch compilation

I am currently exploring the use of Pure.css in my application. After installing it via npm, I have configured my brunch-config.js as follows: stylesheets: { joinTo: { 'app.css': /^app/, 'vendor.css': /^(?!app)/ } } At thi ...

How can I make a method in VueJS wait to execute until after rendering?

There is a button that triggers the parse method. parse: function() { this.json.data = getDataFromAPI(); applyColor(); }, applyColor: function() { for (var i=0; i<this.json.data.length; i++) { var doc = document.getElementById(t ...

Avoiding the page from scrolling to the top when the sidebar is opened (NextJS, Typescript, TailwindCSS)

I'm currently working on a website that features a sidebar for smaller screens. While the sidebar functions properly, I would like to keep the background page fixed in place when the sidebar is active so it does not scroll. In my code, I have utilize ...

I'm a complete programming newbie and I want to start learning JavaScript, jQuery, and other programming languages. Where should I

Coming from a design background with zero programming knowledge, I have recently learned XHTML and CSS. Now, I am eager to expand my skills by mastering JavaScript, jQuery, and more. Where should I begin? This will be my first foray into programming. Whil ...

Can you tell me if there is a switch available for hover or mouse enter/mouse leave functions?

I have a series of div elements, each containing several nested div elements. I would like to add hover effects to these div elements. However, I am unsure whether to use the hover or mouseenter function. For instance, when hovering over a div, I want it t ...