Issue: Unable to change onclick event using JavaScript I am facing a

Presently, I have this code snippet:

function tp_visible(action){
    if(action==1){
        document.getElementById("tp").style.display='block';
        document.getElementById("tp_action").onclick='tp_visible(0);
        return false;';
    }
    else {
        document.getElementById("tp").style.display='none';
        document.getElementById("tp_action").onclick='tp_visible(1);
        return false;';
    }
    return false;
}

However, the onclick event is not changing as expected.

When inspecting with Firebug, it appears that the event remains unchanged...

Below is the corresponding HTML element:

<a
    id='tp_action'
    name='tp_action'
    href='#'
    onclick='tp_visible(1);
    return false;'
>Show info</a>

Answer №1

This solution will be effective for your situation as trying to set a string value to the handler onclick is not possible.

function toggleVisibility(action){
    if(action==1){
        document.getElementById("tp").style.display='block';
        document.getElementById("tp_action").onclick= function ()
            { toggleVisibility(0); return false;};
    }
    else {
        document.getElementById("tp").style.display='none';
        document.getElementById("tp_action").onclick= function ()
            {toggleVisibility(1); return false; }
    }
    return false;
}

Answer №2

For those new to Javascript, I recommend familiarizing yourself with one of the many exceptional javascript libraries available instead of attempting to write everything from scratch - it can be quite overwhelming.

Additionally, it wouldn't hurt to consider getting a copy of "Javascript the Good Parts" and watching videos by Douglas Crockford.

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

Difficulty in sharing cookies among subdomains

I have successfully stored my visitors' style sheet preference in a cookie, but I am facing an issue with sharing the cookie across subdomains. Even after specifying the domain, the cookie does not seem to be shared. What could be causing this proble ...

Encountered an error with the opcode during deployment of migrations

Encountering an error while running the truffle migration command, despite trying several solutions without success. PS C:\Users\Jatin\OneDrive - nsut.ac.in\Desktop\Truffle\web> truffle migration Compiling your contracts... ...

JavaScript returns the value 'undefined' when a function variable is used with an array of objects

Here is an example of an array of objects: var theArray = [ {theId:'1', num: 34}, {theId:'2', num: 23}, {theId:'5', num: 26} ]; This function successfully loops through the array: function printValues() { va ...

How to perfectly align a modal box in the center

Hey everyone, I could really use some help. I'm struggling to find the right formula to center this modal (http://www.queness.com/post/77/simple-jquery-modal-window-tutorial) on my browser, which has a size of 1263X582. I've been trying to use th ...

The visibility of JavaScript script to Tomcat is obscured

Working on a web project using servlets and JSP in IntelliJ. One of the JSP files manages graphics and user forms with graphics.js handling graphics and form validation done by validator.js. The issue I'm facing is that while Tomcat can locate graphi ...

Sorting elements in an array based on an 'in' condition in TypeScript

I am currently working with an arrayList that contains employee information such as employeename, grade, and designation. In my view, I have a multiselect component that returns an array of grades like [1,2,3] once we select grade1, grade2, grade3 from the ...

Retrieving Information with the Fetch API in Node.js and Storing it in a MongoDB Database

I'm a newcomer to mongooseDB and am currently experimenting with inserting data from an API into the database. It successfully creates the Collection, but unfortunately it is not generating the documents. Any suggestions on what I might be doing incor ...

Ensuring that toggleClass is consistently displayed for all visitors to the website

Is there a way to make toggleClass save and remain for all visitors of the site? Although I tried, this method appears to be not working: https://jsfiddle.net/715j94gL/3/ $(function(){ $(".worker").click(function(){ $(this).toggle ...

A guide on implementing the intl-tel-input plugin within an Angular 2+ project

Component : ng2-tel-input, Framework : Angular 4, JavaScript library : intl-tel-input Upon completing the installation with npm i ng2-tel-input I stumbled upon a note in the node_modules\intl-tel-input\src\js\intlTelInput.js file that ...

Unlock the ability to retrieve the current Ember route directly within a component

I have a unique custom Ember component embedded within a controller. Currently, I am attempting to dynamically retrieve the name of the current route. In order to access the controller, I use: this.get('parentView') However, I am facing diffi ...

Steps for implementing AJAX to display a success function and update database results in real-time

I'm struggling with allowing my AJAX call to send data to my PHP file and update the page without a reload. I need the success message to display after approving a user, but their name doesn't move on the page until I refresh. The goal is to app ...

Utilizing Flask's get and post methods in conjunction with AJAX integration

I am in the process of developing a food calorie web application and would like to extract data from a MongoDB database into an HTML table. This is my python code: from flask import Flask from flask import request import requests from wtforms import Form ...

Obtain the content enclosed by HTML tags

Looking to extract text between html tags? Imagine having a list of cities in California, each within paragraph tags. Can you retrieve only the text inside the paragraph tags? <div class="cities"> <div><p>Los Angeles</p><h5 ...

I am looking to eliminate any special characters from a designated section of a string using Javascript

I have a string that looks like this: var myString = '{"key1":"value1", "key2":"value2", "key3":"value3"}'; My objective is to remove double quotes and other special characters only from value3. Sometimes the string may look like: var myStrin ...

Adding data to a URL using jQuery Ajax

I'm currently working on implementing Ajax with jQuery and I have a specific requirement to add data to the URL. Take a look at the code snippet below: var my_website= mysamplesite.com/viewData/"; function displayData(myData) { $.ajax({ t ...

Exploring data that is nested within its parent

I'm struggling to understand the concept of Nested selections or how to apply it to my specific situation. Here is an example of the JSON data format I am working with: { 'name': 'root' 'children': [ { &ap ...

"Encountered a corrupt XLSX file when attempting to download through Vue.js with Axios

Hey there, I've been attempting to generate a download using axios for an excel file but unfortunately, I haven't been successful in opening it. Could you please assist me in identifying the problem? const blob = new Blob([result.data], { ty ...

Using webpack with the production parameter

Currently working on an Express+React application which utilizes webpack for bundling. During development, I have been using "webpack --watch", but as I prepare to deploy to production, I am interested in uglifying my JavaScript code. Unfortunately, the ...

What is the best way to prevent the page from constantly refreshing?

Recently, I developed a code snippet that detects the user's geolocation and changes the currency accordingly. The functionality works as intended, but there is an issue where the page keeps refreshing due to the presence of certain code. If I remove ...

Avoid using the `target` attribute for `onclick` in Material UI components with React

Here is my current situation: The material UI component does not target my attribute on click. I am using the following button: <FlatButton containerElement="button" className="selectedNumberOfPeopleButton" onClick={this.selectedNumberOfPeople ...