how to avoid rewriting java script code?

javascript function
javascript dynamic function
javascript best practices
javascript best practices 2019
rewrite javascript function
explain dynamic function creation in javascript
javascript create dynamic function with parameters
is not a function javascript onclick

I am looking for a way to avoid rewriting the same code again and again. I am making a web page that has divs with hide and show option, with the help of a button you toggle between hide and show. I found an easy way to achieve the effect with this code:

function myFunction() {
  var x = document.getElementById("myDIV");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>

<button onclick="myFunction()">Try it</button>

<div id="myDIV">
  This is my DIV element.
</div>

<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>

Easy, parameterize the id:

function myFunction(divId) {
    var x = document.getElementById(divId);

and in the HTML pass the id to the function:

<button onclick="myFunction('myDIV')">Try it</button>
<div id="myDIV"> ...</div>

<button onclick="myFunction('myOtherDIV')">Try it</button>
<div id="myOtherDIV"> ...</div>

... and so on ...

You can keep one single function and handle as many divs as you want.

JavaScript best practices, Avoid globals. Global variables and function names are an incredibly bad idea. The reason is that every JavaScript file  Or just ignore the message by using the loopfunc option: – kudlatiger Apr 27 '16 at 5:25. @codetoshare The message is there for a reason. You should avoid defining functions in a loop since each loop iteration in the above case will create a new anonymous function when in reality, only 1 function should suffice.


You could run the javascript function with a parameter. So you only have one function and then you only need to change the parameter name. See the example below.

function myFunction(div) {
    var x = document.getElementById(div);
    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
}
<body>

  <p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>

  <button onclick="myFunction('myDIV')">Try it</button>
  <button onclick="myFunction('myDIV2')">Try it2</button>

  <div id="myDIV">
    This is my DIV element.
  </div>

  <div id="myDIV2">
    This is my DIV2 element.
  </div>

  <p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>

</body>

JavaScript Functions That Define and Rewrite Themselves, The dynamic nature of JavaScript means that a function is able to not the browser, and avoid checking for features every time they're invoked. With client-side JavaScript, one can set a breakpoint right where it sets the value. This breakpoint gets hit right as the event fires. The value that gets set through var value = '2'; can change at will. The debugger halts execution and allows a person to tamper with the page.


Just pass the div id to a function

function toggleDiv(divId) {
    var x = document.getElementById(divId);
    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
}

This works perfectly but gets a bit tedious when you have a dozen or more divs with said effect

Create an array of such div ids to be toggled and iterate the same, for example

var divIds = ["myDIV1", "myDIV2", "myDIV3"];
divIds.forEach( s => toggleDiv(s) );

JavaScript for Cats, There is also a lot of JavaScript code available that is not built in. JavaScript from a JavaScript value. My own rule of thumb is to try to keep the two types of functions separate from each other, so here's how I would rewrite the yellIt function: Avoid Using eval() The eval() function is used to run text as code. In almost all cases, it should not be necessary to use it. Because it allows arbitrary code to be run, it also represents a security problem.


Pass a parameter into the function.

function myFunction(divName) {
    var x = document.getElementById(divName);
    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
}
<body>

<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>

<button onclick="myFunction('myDIV')">Try it</button>

<div id="myDIV">
This is my DIV element.
</div>

<button onclick="myFunction('myDIV2')">Try it</button>

<div id="myDIV2">
This is my DIV2 element.
</div>

<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>

</body>

Buggy JavaScript Code: The 10 Most Common Mistakes , If you need help figuring out why your JavaScript isn't working, consult this list of the 10 to be aware of and avoid in one's quest to become a master JavaScript developer. clearBoard is not a function, while in my rewritten example, this. Taking a look at the code, is there a better way in JavaScript to prevent so much repetition. In particular, re declaring the variables like moduleOptions, removeBtn, moveUp? I tried putting them in their own key values pairs.


using event target and operating relatively on elements, can do the task.

<!DOCTYPE html>
<html>
   <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>JS Bin</title>
   </head>
   <body>
      <p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
     
      <hr>
     
      <div class="wrapper">
        <button onclick="myFunction(event)">Try first</button>
        <div class="content">
           This is my DIV element.
        </div>
      </div>
     
     <hr>
     
     <div class="wrapper">
        <button onclick="myFunction(event)">Try second</button>
        <div class="content">
           This is my DIV element.
        </div>
      </div>
     
     <hr>
      
     <p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>
      <script>
         function myFunction(event) {
             var wrapper = event.target.parentElement;
             var content = wrapper.querySelector('.content');
             if (content.style.display === "none") {
                 content.style.display = "block";
             } else {
                 content.style.display = "none";
             }
         }
      </script>
   </body>
</html>

Rewriting JavaScript Content, One other way JavaScript code is used to manipulate URLs is The leading period is still included to avoid accidentally rewriting of other  I guess it depends what code you’re re-writing, what it does, and why you’re re-writing it. I think the only general advice I would give is not to simply write Javascript in Java syntax.


JavaScript Best Practices Part 1 · Thinkful Programming Guides, Avoid describing a value with your variable or function name. You run the danger of your code being overwritten by any other JavaScript added to the page after yours. Good code should be easy to build upon without rewriting the core. JavaScript Functions That Define and Rewrite Themselves The following is a short extract from our new book, JavaScript: Novice to Ninja, 2nd Edition , written by Darren Jones. It’s the ultimate


Functions, They allow the code to be called many times without repetition. example clearly demonstrates one of the main purposes of functions: to avoid code duplication. Rewrite it, to perform the same, but without if , in a single line. JavaScript is a truly amazing tool for front-end programming, creating interactive, feature-rich websites and fast, seamless web applications. Every front-end developer knows JavaScript, but when used without caution or expertise, it can be a double-edged sword. Poorly written JavaScript code can slow your website, negatively affecting load times and rendering speed. In this article, we'll


How to Rewrite a JavaScript Function into a jQuery Plugin, Writing a jQuery plugin is not hard & it keeps the code clean if you write everything in jQuery. Learn how to rewrite plain JS functions into jQuery plugins. no technical reason for that – keep your small plugins wherever you  JavaScript statements are commands to the browser JavaScript code is a sequence of statements JavaScript statements are separated with semicolon Multiple statement on one line is allowed JavaScript statements can be grouped together in code blocks You can break a code line after an operator or a comma.