How to Disable Functionality Using a Different Function in Vanilla JavaScript

Is there a way to disable one function with another in JavaScript? I have a form that shows additional coursework inputs only if the user has completed extra work, but I want to add a failsafe in case they change their mind.

I need assistance in writing a failsafe function that checks if the first function has been triggered and then disables it.

CodePen: http://codepen.io/theodore_steiner/pen/ORzpQQ

 function hideCourseWork() {
   var otherEducationHistory = document.getElementById("otherEducationHistory");
   otherEducationHistory.style.display = "none";

   if (otherEducationHistory.style.display == "none") {
     var noAdditionalCourseWork = document.getElementById("noAdditionalCourseWork");

     var checkNo = document.getElementById("checkNo");

     var undo = document.getElementById("undoNoAdditionalCourseWork");

     noAdditionalCourseWork.style.top = "-48px";
     checkNo.style.top = "-65px";
     undo.style.top = "-65px";
     undo.style.top = "-63px";
   }

 };
<div class="input-group" id="other-education">
  <p class="subtitleDirection">Please list in chronological order, any additional cources beyond the degree(s) listed above, including any Ministry of Education Courses. If you have not completed any additional course work, please indicate.</p>
  <div class="clearFix"></div>
  <label id="otherEducation">Additional Courses*</label>
  <div id="otherEducationHistory">
    <input type="text" class="three-lines" name="otherUniversity_1" placeholder="Institution" onblur="this.placeholder='Institution'" onfocus="this.placeholder=''" />
    <input type="text" class="three-lines" name="otherDegree_1" placeholder="Degree/Diploma" onblur="this.placeholder='Degree/Diploma'" />
    <input type="date" class="three-lines" name="otherEducationYear_1" />
    <input type="button" value="+" onclick=addOtherEducation() />
  </div>
  <!--end of otherEducationHistory div-->

  <div class="clearFix"></div>
</div>
<!--end of other-education div-->

<p id="noAdditionalCourseWork">I have not completed any additional course work.</p>
<input type="radio" name="checkNo" id="checkNo" onclick="hideCourseWork()" />
<br />
<p id="undoNoAdditionalCourseWork" onclick="reAddCourseWork()">(Undo).</p>

Answer №1

Your question is a bit unclear, but here's some clarification that might help.

Functions can be thought of as similar to variables in that they can be reassigned, such as to an empty function.

function doSomething(){
    alert("didSomething");
}

function disableDoSomething(){
    window.doSomething = function(){};
}

If you need to re-enable the function at a later point, you can use this approach:

function doSomething(){
    alert("didSomething");
}

var functionHolder;
function disableDoSomething(){
    if(!functionHolder) functionHolder = window.doSomething;
    window.doSomething = function(){};
}

function enableDoSomething(){
        window.doSomething = functionHolder;
    }

Answer №2

let exampleFunction = () => { /* defining an example function */ },
    anotherFunction = exampleFunction;

/* changing the implementation of exampleFunction to an empty function, effectively disabling it */
exampleFunction = () => {};

/* ... code that utilizes the function reference exampleFunction ...*/

/* re-enabling the original behavior of exampleFunction by assigning anotherFunction back to it */
exampleFunction = anotherFunction;

For archival purposes (ES5):

var exampleFunction = function() { /* defining an example function */ },
    anotherFunction = exampleFunction;

/* changing the implementation of exampleFunction to an empty function, effectively disabling it */
exampleFunction = function(){};

/* ... code that utilizes the function reference exampleFunction ...*/

/* re-enabling the original behavior of exampleFunction by assigning anotherFunction back to it */
exampleFunction = anotherFunction;

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

Creating a custom JavaScript grid from the ground up

I'm intrigued to learn about the process of creating a JavaScript grid from the ground up. This grid should include features similar to jqGrid found at http://www.trirand.com/blog/jqgrid/jqgrid.html. Could someone kindly provide me with some guidance ...

Activate a timer as soon as the page is first loaded. The timer must continue running from the initial load even if the user leaves

Looking to implement a time-limited offer on the first stage of our checkout process. The timer should start at 5 minutes when the page loads and continue counting down even if the user leaves the page and returns. Has anyone come across a script that can ...

What are the best practices for creating and displaying functional components effectively?

I'm in the process of building and displaying a functional component following the guidelines provided as a starting point. After reviewing the instructions, it seems like I should be able to achieve something similar to this: class MyComponent exten ...

Tips for passing an object by value to an Angular2+ component

Imagine having a scenario where I create a component that takes a Foo instance and generates a form for editing. export class ChildComponent implements OnInit { @Input() foo : Foo; @Output() onChange : EventEmitter<Foo> = new EvenEmitter<Foo& ...

What was the functionality of visibilitychange implemented for?

Here is my query: window.addEventListener("visibilitychange", function(e) { console.log(window.uidd) window.uidd = window.uidd || (new Date).getTime() + Math.random() console.log(window.uidd) }) However, if you open the console for the first time ...

JavaScript Function Call Crashes Script

Currently, I am delving into the world of JavaScript by exploring . I find it beneficial to tackle the exercises provided before progressing to the next chapter as a way to practice. After completing chapter 4 and reviewing the exercises found at the end ...

React Native (or React) utilizes separate TypeScript modules to detect and respond to style adjustments for dark mode

Objective: Add a dark mode feature to a react native application. A brief overview of the system: File structure: Profile.ts ProfileCss.ts constants.ts In my app, I've organized styles in separate .ts files and exported them as modules to keep them ...

Tips for creating query requests in ExpressJS

Can someone provide the correct command to write in an ExpressJS file in order to expose a single HTTP endpoint (/api/search?symbol=$symbol&period=$period)? Here is what's currently working: app.get('/api/search/', (req, res) => ...

Discovering the quantity of pagination tabs in Selenium WebAutomation

A critical element in the table "ContentPlaceHolder1_gvChannelList" is Pagination, located at the last row. I need to determine how many pages/columns are present in this pagination table. The code driver.findElements(By.id("//*[@id='ContentPlaceHold ...

Transform the styles from a React component into Cascading Style Sheets

I have been tasked with transitioning all the styles from the JavaScript file to the CSS file while ensuring the design remains intact. I am facing an issue where using the CSS styles breaks the search field design. The original design can be seen here: S ...

How can I center an image next to text on two lines, that is compatible with IE7?

I am trying to align an image (logo) with text in two lines - the website title and a brief description. Here is my attempt using HTML: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional ...

The window resizing function continues on an endless loop

I could really use some assistance in pinpointing the issue at hand! My script is set up to display a banner at the top of a page only if the window width is 600px or less and the scroll position is within 34px from the top. It hides the banner when the u ...

What are the steps for running app.js deployed on a remote server using the local bash terminal?

After launching my web application on GoDaddy, which is built in Node.js, I have encountered a dilemma. In order to run app.js, I currently rely on my computer's bash command prompt. However, this poses an issue - if I were to shut down my laptop, the ...

Retrieve an image from an external web service and transfer it to a different route in Express.js

I am facing an issue with passing an image object from an external web service through a node express route. The specific problem I am encountering involves retrieving an image from a URL and attempting to pass it as is, but it seems to be not functioning ...

Using jQuery and CSS to change to "loading" status

My current setup includes the following: <div class="click red"></div> <div class="click green"></div> <div class="click blue"></div> When the "click" is clicked, I want to add the class "load" to the div. I have succe ...

React component fails to display content following execution of Jquery Ajax request

Utilizing a basic jQuery ajax function to retrieve inline HTML code from an API $.ajax({ url: url, headers: { 'Accept': 'application/javascript' }, dataType: 'html', beforeSend: function(){ $('.load-mor ...

Troubleshooting Problems with Loading Data into Highcharts using Javascript

The server is returning data in the following format: {"barData": [ {"Accepted":[0,0,0]}, {"Rejected":[0,0,0]}, {"In_Process":[0,1,0]}] } On the browser, it appears as follows: I initially thought that this was the correct st ...

What strategies can be implemented to minimize the use of if-else statements?

Is there a more efficient way to simplify this if-else statement? This code dynamically changes the picture based on integers retrieved from the database. I am looking for ways to optimize this code. if (val["soil_h"] < 21){ $("#ground").att ...

Retrieving the value of the selected item when it is changed

I am currently using v-select/v-autocomplete in my project: <v-autocomplete v-modal="newRole" :items="roles" label="--Change role--" required return-object item-value="id" item-text=&qu ...

What could be causing my css stylesheet to not function properly in Sinatra?

I'm fairly new to this, but based on my research, this code should be functioning correctly. I am attempting to link a CSS stylesheet to an .erb file. Here is the code snippet I am using: <link rel="stylesheet" type="text/css" h ...