Javascript does not execute onclick event

I have some simple javascript functions:

function focus(id) { var e = document.getElementById(id); if (e != null) { e.focus(); } } function show(id) { var e = document.getElementById(id); if (e != null) { e.style.display = "inline"; } } 

Then I have an html tag with an onclick event.

 <a title="Click This" onclick="focus('some_textbox'); show('some_panel');">Click This</a> 

When I click the "Click this link" link, only the show () method is executed. For some reason, the focus method is never called. Any idea why this is happening?

I tried to clear my cache and reordered the focus () and show () methods. I also confirmed that everything is spelled correctly.

Is it because focus () is already a function inside javascript?

Edit: I tried to rename the function to focus2, and now it works. Very strange. Does anyone know why this is happening?

+4
source share
2 answers

It looks like you have a renaming problem.

Just rename the focus function to focusX or something else, this works for me in my test case.

Remember to update focus call in href, focusX

0
source

It probably calls the focus method, but what happens is that the default action of the <a> tag steals it back. Try the following:

 function focus(id) { var e = document.getElementById(id); if (e != null) { setTimeout(function() { e.focus(); }, 1); } } 

By launching the "focus" call in a separate event loop, you can make sure that your element captures focus after the "click" processing is completed.

+3
source

Source: https://habr.com/ru/post/1388679/


All Articles