button button click

Welcome to button button click

javascript - Set click event for function to button - Stack Overflow

2024.10.04 11:29


Skip to main content Stack Overflow About Products OverflowAI Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand OverflowAI GenAI features for Teams OverflowAPI Train & fine-tune LLMs Labs The future of collective knowledge sharing About the company Visit the blog

current community

Stack Overflow help chat Meta Stack Overflow

your communities

Sign up or log in to customize your list.

more stack exchange communities

company blog Log in Sign up Home Questions Tags Users Companies Labs Jobs Discussions Collectives

Communities for your favorite technologies. Explore all Collectives

Teams

Now available on Stack Overflow for Teams! AI features where you work: search, IDE, and chat.

Learn more Explore Teams Teams

Ask questions, find answers and collaborate at work with Stack Overflow for Teams. Explore Teams

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

Get early access and see previews of new features.

Learn more about Labs

Set click event for function to button

Ask Question Asked 5 years, 9 months ago Modified 5 years, 9 months ago Viewed 3k times 0

I have a button that I would like to assign a click event to, so that when I click on the button it will run the function.

button id="buttonid" /button

When I run the script below it will trigger the function, but the click event will not be added to the button. So I cannot use the button to trigger the function.

function myFunction() { alert("Hello, world!"); } var element = document.getElementById("buttonid"); element.onclick = myFunction;

I believe my goal would look like this:

button id="buttonid" onClick="myFunction()"

javascript function buttonclick Share Improve this question Follow asked Dec 17, 2018 at 14:36 Joe Berg Joe Berg 381 6 6 silver badges 19 19 bronze badges Add a comment |

2 Answers 2

Sorted by: Reset to default Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first) 3

Your initial code should work, provided that it is run after the DOM is ready so that the document.getElementById("buttonid"); actually finds the element.

Check your console for errors that might indicate that element is undefined .

To make sure move the script tag that includes your code at the bottom ( right before closing the body tag )

After the above a better approach is to not set the onclick attribute but instead use the addEventListener method.

body button id="buttonid" clickme /button script function myFunction() { alert("Hello, world!"); } var element = document.getElementById("buttonid"); element.addEventListener('click', myFunction); /script /body

Share Improve this answer Follow answered Dec 17, 2018 at 14:39 Gabriele Petrioli Gabriele Petrioli 195k 34 34 gold badges 270 270 silver badges 325 325 bronze badges 4 Hi Gabriele, thank you for your answer. I tried both your and my example above, and both actually works if I try to run them from console in Chrome here on stackoverflow. But at least my example above didn t work in Safari at work, and the DOM is ready, as I waited for the page to load before injecting the script from console, and the button id is also correct. In my case above, would it matter if 1. it s Safari browser, 2. injected by a script/extension or 3. the buttons are replaced spans: stackoverflow.com/questions/53803268 you can read here where I replaced the spans with buttons – Joe Berg Commented Dec 17, 2018 at 16:05 My end goal is to have the replaced spans (which are now buttons) clickable and have the same function assigned to all of them. The function will behave differently dependent on what is in the inner text of each button. – Joe Berg Commented Dec 17, 2018 at 16:10 @JoeBerg It will not work with the code in that answer. You need to alter that script to maintain the id of the span to the button and run the code that adds the event handler after the code that replaces the spans. – Gabriele Petrioli Commented Dec 17, 2018 at 16:23 1 Thanks for pointing that out Gabriele, that should have been the issue. I used the same method as in the other question to assign a new id to the buttons, and it worked now. :) – Joe Berg Commented Dec 18, 2018 at 6:23 Add a comment | 0

Try this:

function myFunction(e) { alert("Hello, world!"); console.log(e); } button id="buttonid" onclick="myFunction(event)" Click me /button If you wanna add event handler from js code then that code should be included blow your html with button.

Share Improve this answer Follow edited Dec 17, 2018 at 14:44 answered Dec 17, 2018 at 14:39 Kamil Kiełczewski Kamil Kiełczewski 91.1k 32 32 gold badges 392 392 silver badges 362 362 bronze badges Add a comment |

Not the answer you're looking for? Browse other questions tagged javascript function buttonclick or ask your own question .

The Overflow Blog A developer works to balance the data center boom with his climate change battle Community Products Roadmap Update, October 2024 Featured on Meta Preventing unauthorized automated access to the network Upcoming initiatives on Stack Overflow and across the Stack Exchange network Feedback Requested: How do you use the tagged questions page? Proposed designs to update the homepage for logged-in users

Linked

0 How to replace specific tags that contains selected labels

Related

1 assign onclick event to function 0 specifying function as the event handler for button 0 How to associate Javascript functions with buttons? 0 Assign onclick to a function issue 0 run function when button clicked 1 Javascript linking a function to the click of a button 0 Make a function that recognises which button is clicked 0 Calling Javascript function on button click 0 Button onclick in function 0 JavaScript button click event

Hot Network Questions

Is this link a scam ? gbr01.safelinks.protection.outlook.com/? Should I use the speaker's native language for single word exclamations? Problems with bibliography in article class How important is research-fit in post-doc hiring Dynamic Arrays with Count / Capacity in C During WWII, did the Allies know about the location and significance of the Wolf's Lair? If so, why did they not attack it? Is the anthropic principle a cop-out? How to use container in WSL 2, without installing the Hyper-v feature? An intensional system of meaning for predicates? (And related thoughts) Can I get my DEX on dual wield bonus attack using Nick? Emulate gron using jq This housing tech can rapidly print its own interior environments with an invisible 3D-printing swarm. Why isn't this tech everywhere? How do handle maximum in a quadratic programming problem by adding auxiliary variables? Why is unbiased estimator more important than min-error estimator? Are tyres truly the best upgrade for a bike? Mate in 2 by Vladimir Nabokov Do any hobbits ever use Sie in German translations of The Hobbit or The Lord of the Rings? Can you wear the chain/cassette by always riding in the same gear? Why did Boeing shrink the bottom of the engine casing instead of the whole casing? Which symmetry corresponds to the conservation of particle number in real scalar field theory? Is this amount of chain slack normal? Select foreign language for all cells in one column of table? Foreign street names in Japanese What happens if I move an object that has Darkness cast on it? more hot questions Question feed

Subscribe to RSS

Question feed

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

lang-js
Stack Overflow
Questions Help Chat
Products
Teams Advertising Talent
Company
About Press Work Here Legal Privacy Policy Terms of Service Contact Us Cookie Settings Cookie Policy
Stack Exchange Network
Technology Culture & recreation Life & arts Science Professional Business API Data Blog Facebook Twitter LinkedIn Instagram

Site design / logo © 2024 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2024.10.3.16276



Vivamus fermentum nibh