Is there a presence of performance or accessibility challenges within this jQuery/HTML script?

I have tested the following code across various browsers like IE, FF, Chrome, and Safari, and it seems to work fine. However, I am concerned about its efficiency when scaled to accommodate a large number of users. Additionally, I'm wondering if this code is accessible to screen readers and users with special needs. Is there a more efficient way to write the jQuery without using excessive $(this) references? Would reducing the number of $(this) calls impact performance? Also, will setting the display property to none on the labels affect accessibility for screen reader users? Although I set title attributes during page load for their benefit, I wonder if this practice serves any purpose or is even necessary. Lastly, I acknowledge that all these features would be rendered useless if JavaScript is disabled, but I still want to inquire.

<html>
    <head>
        <title></title>
        <style type="text/css">
            fieldset {
                border: none;
                padding: 10px;
                width: 600px;
                margin-top: 5px;
            }

            label { 
                display: none;
            }

            input {
                width: 150px;
                margin: 5px;
                float: left;
                display: block;
            }

            br {
                clear: both;
            }
        </style>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                GetInputLabels();
                $("input").focus(function() {
                    if ($(this).val() == $(this).prev("label").text()) {
                        $(this).val('').css("color", "#000");
                    }                   
                });
                $("input").blur(function() {
                    if ($(this).val() == '') {
                        $(this).val($(this).prev("label").text()).css("color", "#bbb");
                    } 
                });
                function GetInputLabels() {
                    $("input").each(function() {
                        var label = $(this).prev("label").text();
                        $(this).val(label).css("color", "#bbb").attr("title", label);
                    });
                }
            });
        </script>
    </head>
    <body>
        <form>
            <fieldset>
                <label for="fname">First Name</label>
                <input id="fname" type="text" /> <br/>

                <label for="lname">Last Name</label>
                <input id="lname" type="text" /> <br/>

                <label for="email">Email</label>
                <input id="email" type="text" /> <br/>
            </fieldset>
        </form>
    </body>
</html> 

Answer №1

It seems like your code is in good shape, but there are a few optimizations you can implement to improve performance. One suggestion is to cache jQuery DOM elements to reduce unnecessary DOM traversals. Additionally, chaining events can help minimize the number of lookups required:

var input = $('input');
input.focus(fn).blur(fn)...

Another tip is to cache this to prevent extra jQuery calls:

var context = $(this);

If you need to hide elements without affecting screen readers, it's best to use

position:absolute; left:-10000px;
instead of display:none.

Below is an optimized version of your script:

jQuery(function($) {

    var input = $('input');
    var GetInputLabels = function() {
        input.each(function() {
            var elem = $(this);
            var label = elem.prev('label').text();
            elem.val(label).css("color", "#bbb").attr("title", label);
        });
    }

    GetInputLabels();

    input.focus(function() {
        var elem = $(this);
        if (elem == elem.prev('label').text()) {
            elem.val('').css("color", "#000");
        }                                       
    }).blur(function() {
        var elem = $(this);
        if (elem.val() == '') {
            elem.val(elem.prev("label").text()).css("color", "#bbb");
        } 
    });
});

Answer №2

To optimize your code, consider setting var element = $(this); at the start of your anonymous functions and then using this variable throughout the function. This will help reduce unnecessary lookups.

In regards to screen readers, hiding labels with visibilty: hidden or display: none will prevent them from being read aloud. A better approach would be to position them offscreen for regular users using a position:absolute solution. For more information on this technique, check out the following link:

Answer №3

Ensuring that you cache your DOM queries is a crucial step to remember. Another helpful practice is chaining together your code for efficiency.

let inputs = null;
function fetchInputs() {
    if (inputs === null) {
        inputs = $("input");
    }

    return inputs;
}


$(document).ready(function() {
    fetchInputs().each(function() {
        let element = $(this);
        let label = element.prev("label").text();
        element.val(label).css("color", "#bbb").attr("title", label);
    }).focus(function() {
        let element = $(this);
        if (element.val() == element.prev("label").text()) {
             element.val('').css("color", "#000");
        }                                       
    }).blur(function() {
        let element = $(this);
        if (element.val() == '') {
            element.val(element.prev("label").text()).css("color", "#bbb");
        } 
    });
});

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

Prevent the repositioning of a tooltip due to overflow in Bootstrap 5.2 and Popper JS Tooltips

Can someone please provide an example of how to create a tooltip using Bootstrap 5.x and Popper JS, where the tooltip remains fixed to the associated element even if the page overflows and scroll bars appear? I've attempted to work with boundaries an ...

How do I retrieve the class of an element nested within another element using jQuery?

If we consider a scenario where there is a table named unitTables with various rows, each containing the selected class that we want to retrieve for a variable. This specific table is just one of many similar tables on the webpage. Since other tables also ...

Pytest is not able to locate any elements on the webpage, yet the same elements can be easily found using the console

When using CSS or XPath in the console (F12), I am able to locate the element on the page. $$("span.menu-item[data-vars-category-name='Most Popular']") However, when trying to find the same elements with Selenium (pytest) using: driver.find_el ...

Trouble with AJAX BitMovin: unable to process GET request

I've been struggling to find a solution to my problem as I cannot pinpoint what exactly to search for. My current issue involves using AJAX for a PHP Get request, causing it to submit and navigate away from the page. The BitMovin library appears to b ...

Want smooth transitions between pages?

I need assistance with implementing swipe navigation for my app. Unfortunately, the code I currently have appears to be faulty. This is only my second attempt at creating an app and any guidance would be greatly appreciated. I am having difficulty sharing ...

Issue with SwiperJS not completely filling the height of a div

My issue relates to using swiperJS with multiple images, as I'm struggling to make it take the full width and height of the containing div. Despite applying styling like this to my images: .swiper-slide img { width: 100%; height: 1 ...

What is causing the navigation bar on stackoverflow.com to move suddenly when clicked?

Just noticed the sleek new navigation bar on stackoverflow. Reminds me of the bootstrap design I've been using. However, I've encountered a similar issue on my website where the navigation bar jumps slightly when clicked. Does anyone have any su ...

What steps can I take to generate 12 random div elements using jQuery out of a pool of 30?

Currently, all the words are displaying, but I would like the script to randomly select 12 out of the 30 words var randomdivs = $("wordstyle").get().sort(function(){ return Math.round(Math.random())-0.5; }).slice(0,12) $(randomdivs).show(); The follo ...

Automatically submit using Braintree Custom Form through programming

Incorporating Braintree custom form inside a Bootstrap modal has been working smoothly for me. Currently, the form functions properly with a submit button placed within it. Upon clicking the submit button, Braintree takes over and carries out its submissio ...

What is the process for extracting data from a jQuery function?

I've created a script to search for products using select2 plugin <script type="text/javascript> $( document ).ready(function() { $("#productSelect").select2({ placeholder: 'Select a Product', minimumInputLength: 3, ajax ...

The compatibility of IE9 with tables and the use of display: block

When optimizing my site for low-width mobile devices, I adjust the display property of various table elements such as tr, td, and th to block in order to stack them vertically. This technique helps wide tables to show all their content without overflowing ...

Implementing validation for multiple email addresses in JavaScript: A step-by-step guide

Currently, I am utilizing Javascript to perform validation on my webpage. Specifically, I have successfully implemented email validation according to standard email format rules. However, I am now seeking assistance in enhancing the validation to allow for ...

Connection between overlay div and corresponding destination div address

I created a linked image with an overlay div: <div class="imageBlock"> <a href="http://www.google.com"> <img src="https://placeimg.com/640/480/any"> </a> <a href="http://www.twitter.com"> <img src="https://pl ...

What's the best way to add Font Awesome icons to your website - using append

I am facing a situation where I need to customize titles with fontawesome icons. For example: <h2 id="test"><i class="fa fa-cog"></i> THIS IS TITLE</h2> I plan to manually add icons to all titles, but if any title is left empty ( ...

The background image is not visible

.imagem-cortada { width: 100%; background-image: url("imagens/Vector 9.png"); } The HTML: <section class="imagem-cortada conteudo-principal"><!--inicio sobre nos--> <div class="container"> ...

After 30 seconds of inactivity, apply the CSS once, then remove it before repeating the process

I've got a unique little CodePen with an animation that I want to execute only if the user hasn't clicked on the <div class="someDiv"> for 30 seconds. My question is, can someone guide me in the right direction so that when someone doesn&a ...

Create a unique inset shadow that surrounds all elements of the content

I'm having trouble figuring out how to create a 4px inset box shadow border that surrounds all of the content. Currently, the box shadow fills the window perfectly (as shown in the fiddle below), but my fixed navigation bar at the top ends up above th ...

Scaling down the screen for a smaller display

Having trouble achieving a specific effect and could use some assistance. My goal is to create an action where, upon clicking on the nav element (for simplicity, I've set it to be triggered by clicking anywhere on the body), the following should occur ...

The iframe came to a halt as soon as it was no

I am currently developing a live video website that utilizes third-party tools to play the videos. To simplify things, I have embedded all the components required for live video into a single HTML page. Here is how it looks: <iframe data-v-140cfad2= ...

How can I handle the issue of the body background overlapping with the modal window?

Recently, I created a dialog box using the code below: $(function(){ $('#saveandcontinue').click(function(){ $('body').css('background', '#999'); $('.footer').css('background&a ...