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

        Write clean jQuery

        469 Views Asked by Subin Jacob At 04 December 2013 at 11:15 2025-12-19T15:35:58.298000

        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

        • Using Puppeteer to scrape a public API only when the data changes
        • inline SVG text (js)
        • An array of images and a for loop display the buttons. How to assign each button to open its own block by name?
        • Storing the preferred font-size in localStorage
        • Simple movie API request not showing up in the console log
        • Authenticate Flask rest API
        • Deploying sveltekit app with gunjs on vercel throws cannot find module './lib/text-encoding'
        • How to request administrator rights?
        • mp4 embedded videos within github pages website not loading
        • Scrimba tutorial was working, suddenly stopped even trying the default
        • In Datatables, start value resets to 0, when column sorting
        • How do I link two models in mongoose?
        • parameter values only being sent to certain columns in google sheet?
        • Run main several times of wasm in browser
        • Variable inside a Variable, not updating

        Related Questions in JQUERY

        • In Datatables, start value resets to 0, when column sorting
        • Bootstrap modal not showing at the desired position on a web page when the screen size is smaller
        • window.location.href redirects but is causing problems on the webpage
        • Using JQuery Date Slider
        • Storing selected language in localStorage
        • How to stop other divs from still showing when i click a different button?
        • Check multiple values with jQuery
        • Bootstrap component does not want to render in Datatables function
        • put white spaces when entering an amount moneytype symfony
        • Trouble accessing custom header in AJAX response using jQuery in Fiware Keyrock
        • I just cant make it work, HTML, JS and Firebase error
        • Didn't declared variable still not getting any error in JavaScript
        • Move element horizontally while scrolling vertically in pure JavaScript
        • allow multi carousel in same page
        • Embedded TikTok posts / thumbnail styling issue

        Related Questions in CODING-STYLE

        • Using Repository pattern to fetch data from different places and build list of objects
        • JavaScript function to validate an email address using regular expressions, ensuring it follows the standard format
        • Suppress "this.field" code style warning only in constructors
        • Need help on how to get my bigger image shown above the thumbnail images after radio botton checked on the thumbnail images without use javascript?
        • What is the 'correct' approach to clean code UI in Delphi Pascal?
        • How do I reduce repetitive error handling in java
        • Is there a solution to a react installation error?
        • Pixela does not let me create graph (HTTP Error: 400) - user does not exist or the token is wrong
        • How can align if statement in cpp with clang?
        • Why Feature Envy sample code in the clean code book is a code smell?
        • is it okay to change the value of parameter inside of method in Dart?
        • NextJS import location styling?
        • INNER JOIN ON LEFT JOIN. What best way solve problem?
        • How to access webtable data in selenium?
        • Suspect code indent for conditional statements

        Related Questions in CUSTOM-DATA-ATTRIBUTE

        • React - getting data-attribute from a a form input field based on object key
        • Jquery DataTable update `data-sort` attribute at runtime not affecting sort
        • jQuery data-attribute to object with stringify reversing on newer versions
        • how to remove a tr where td has a certain data-attr value
        • Does React's type declarations e.g. React.HTMLAttribute<HTMLButtonElement> support the usage of custom data attributes out of the box?
        • How to display some CSS content for div[data-attr="false"]:first-ot-type?
        • On hover get img src specified in a `data` attribute, then add an img + path to another div
        • Function to find out children of multiple HTML elements and use as custom attribute
        • Create custom sharable data within a microsoft graph api event
        • jQuery filtering divs based on multiple data attributes
        • How to compute the total amount of all selected options' custom "data-price"-attribute values?
        • React-Select: Add custom data attribute to Input
        • Creating Accordion in React using Data Attribute Properties, using tailwindcss
        • Plotly Heatmap texttemplate not working with customdata
        • Is there a way to add a blank data attribute to an element using JavaScript?

        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 node.js arrays c asp.net json

        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
        • Pricesm.com
        • Aftereffectstemplates