• " />
    • " />
      • "/>
        DEVHIDE
        • Home (current)
        • About
        • Contact
        • Cookie
        • Home (current)
        • About
        • Contact
        • Cookie
        • Disclaimer
        • Privacy
        • TOS
        Login Or Sign up

        Write clean jQuery

        466 Views Asked by Subin Jacob At 04 December 2013 at 11:15 2025-12-18T00:53:49.140296

        Consider this HTML

        <div id="container">
            <ul id="someID">
            <li id="someID1">
              <div id="someID2">
                <div class="someClass">
                   <label>labelText</label>     
                </div>
              </div>
            </li>
            <li>2</li>
            <li>3</li>
            </ul>
        </div>
        

        and its script

        <script>
        $(function(){
        $("#container label").click(function(){
            $(this).text("labelTextChanged");
        });
        })
        </script>
        

        Let this code written by some one else. And Now I want to change the text labelTextChanged to something new like labelTextChangedThen(This is just an example, sometimes I would need to change a lot of functionality). But now its difficult to find the attached event from the DOM? How can I avoid these kind of problems while writing code in jQuery?

        Is it a good approach to use only attributes (self defined attributes) for selecting elements? (as in Angularjs)

        NB: In reality it may better or worse.

        javascript jquery coding-style custom-data-attribute
        Original Q&A
        4

        There are 4 best solutions below

        4
        KooiInc KooiInc On 04 December 2013 at 11:46 BEST ANSWER

        There are many ways to write clean(er) code. I prefer to separate my handler methods (using named functions) from the handling code, use data-attributes to query and use event delegation. For your example, the code could be rewritten to something like:

        function changeLabelText(e){
            var self = $(this);
            self.text(self.attr('data-changeOnClick'));
        }
        
        $(document).on('click', '[data-changeOnClick]', changeLabelText);
        

        Where <label> would become <label data-changeOnClick="[changed text]">

        In that case, changing the label text later would be as simple as changing the data-changeOnClick attribute in the html. Furthermore, it's easy to add the attribute to any element in your html, which will all trigger the click handler.

        Writing separate handler methods also shows the methods in the aforementioned 'visual event 2' bookmarklet.

        Furthermore, I always load my scripting at the end of the document (right before the closing </body>-tag), to avoid having to wrap method assignment within $(function() {/*...*/} ) or more generally having to use document load-handling.

        See this jsFiddle

        0
        Rituraj ratan Rituraj ratan On 04 December 2013 at 11:17
        <script>
        $(function(){
        $("#container").on("click","label",function(){
          $(this).text("your desired text");
        });
        })
        </script>
        

        and i think to avoid these tyoe code you use visual event 2

        Visual Event is an open source Javascript bookmarklet which provides debugging information about events that have been attached to DOM elements

        reference on()

        0
        bagonyi bagonyi On 04 December 2013 at 11:24

        You can always use the visual event 2 bookmarklet to display the event listeners attached to any DOM element.

        0
        Sawyer Sawyer On 04 December 2013 at 11:43

        For the second question. In my opinion, the use of Id attribute to select dom is a good approach. Because for the elements in the same level, they should not be applied the same Id. And class filter will be good for selecting a group of elements with the same style. for example, you could use $('div[id="xxx"]') to make the code meaningful which means "the div with id equals xxx". For the first question, the code is not easy to read, you could try something like this $('#container').find('.someClass").children('label').click(...). Perhaps it is still not easy for reading the code. But for the code more complicated, the use of plugin will help you to make the project more readable and maintainable.

        Related Questions in JAVASCRIPT

        • Angular Show All When No Filter Is Supplied
        • Why does a function show up as not defined
        • I count the time the user takes to solve my quiz using Javascript but I want the same time displayed on another page
        • Set "More" "Less" font size
        • Using pagination on a table in AngularJS
        • How to sort these using Javascript or Jquery Most effectively
        • how to fill out the table with next values in array with one button
        • State with different subviews
        • Ajax jQuery firing multiple time display event for the same result
        • Getting and passing MVC Model data to AngularJS controller
        • Disable variable in eval
        • javascript nested loops waiting for user input
        • .hover() seems to overwrite .click()
        • How to sort a multi-dimensional array by the second array in descending order?
        • How do I find the fonts that are not loading in a CORS situation ( MoovWeb )?

        Related Questions in JQUERY

        • How to sort these using Javascript or Jquery Most effectively
        • Ajax jQuery firing multiple time display event for the same result
        • .hover() seems to overwrite .click()
        • Check for numeric value with optional commas javascript
        • Extending Highmaps Side Effect
        • Array appending after each onclick and loop in javascript
        • how can i append part of a table based on how many tr it has?
        • Play multiple audio files in a slider
        • Remove added set of rows
        • Access property of an object of type [Model] in JQuery
        • AJAX PHP - Reload div after submit
        • proengsoft/laravel-jsvalidation ReferenceError: jQuery is not defined
        • when a checkbox is checked how to display a different hidden element using javascript
        • Get jquery error Uncaught RangeError: Maximum call stack size exceeded
        • Removing only the closest thead on table filtering

        Related Questions in CODING-STYLE

        • Best practices for creating a huge SQL table
        • Is there a nicer way to do this?
        • Does Elixir have coding standards or an authoritative style guide published by the language developers, like PEP8 or the Erlang Programming Rules?
        • Nesting anonymous delegates in C# - how to make code maintainable and readable?
        • Converting data structures to other data structures
        • Node.js and Q Promises: How can I hand over parameters in a cleaner way?
        • What is the meaning of int[]
        • Where are line breaks allowed within Haskell expressions?
        • VIM - Reformatting indentation and braces
        • How can I define a subprocess in the __init__() part in Python?
        • How to insert values in STL map within a loop
        • Java abstract method: is this bad practice?
        • How to use constant powers of 2 readable in c++?
        • Good practice to explicitly declare variables without 'much' use in favor of readability?
        • Order of functions within a Python source file

        Related Questions in CUSTOM-DATA-ATTRIBUTE

        • Data attributes on IE 9 and older not working on certain instances
        • How can I loop through element's data using jQuery and build these settings?
        • How to use data-image and data-zoom-image attributes in angularjs
        • how to add a data attribute to a formtastic form input radio collection
        • Variable data attribute not working
        • I want to fetch the parent attribute but it returns undefined jquery
        • JQuery Retrive data-attribute from on click function
        • Loop over array of elements, change data attributes
        • Trying to build a jQuery filter using HTML data attributes
        • jQuery getAttribute in IE8 replacement
        • Data-attributes not working in IE
        • How to load data attributes in AngularJS functions?
        • Converting HTML5 data type to number
        • jQuery sorting by data-attribute
        • Custom select box - data-icon not updating properly in placeholder on selection of an option

        Trending Questions

        • UIImageView Frame Doesn't Reflect Constraints
        • Is it possible to use adb commands to click on a view by finding its ID?
        • How to create a new web character symbol recognizable by html/javascript?
        • Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
        • Heap Gives Page Fault
        • Connect ffmpeg to Visual Studio 2008
        • Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
        • How to avoid default initialization of objects in std::vector?
        • second argument of the command line arguments in a format other than char** argv or char* argv[]
        • How to improve efficiency of algorithm which generates next lexicographic permutation?
        • Navigating to the another actvity app getting crash in android
        • How to read the particular message format in android and store in sqlite database?
        • Resetting inventory status after order is cancelled
        • Efficiently compute powers of X in SSE/AVX
        • Insert into an external database using ajax and php : POST 500 (Internal Server Error)

        Popular # Hahtags

        javascript python java c# php android html jquery c++ css ios sql mysql r reactjs

        Popular Questions

        • How do I undo the most recent local commits in Git?
        • How can I remove a specific item from an array in JavaScript?
        • How do I delete a Git branch locally and remotely?
        • Find all files containing a specific text (string) on Linux?
        • How do I revert a Git repository to a previous commit?
        • How do I create an HTML button that acts like a link?
        • How do I check out a remote Git branch?
        • How do I force "git pull" to overwrite local files?
        • How do I list all files of a directory?
        • How to check whether a string contains a substring in JavaScript?
        • How do I redirect to another webpage?
        • How can I iterate over rows in a Pandas DataFrame?
        • How do I convert a String to an int in Java?
        • Does Python have a string 'contains' substring method?
        • How do I check if a string contains a specific word?
        .

        Copyright © 2021 Jogjafile Inc.

        • Disclaimer
        • Privacy
        • TOS
        • Homegardensmart
        • Math
        • Aftereffectstemplates