Why in button tag onclick=methodname is not giving output but onclick=operation gives output

Viewed 58

In the below code if I change background color of Submit button with onclick="document.getElementById('s').style.background='green'" then it changes perfectly but if I do it with function call then it doesn't work which I tried for Clear button. I have commented the functions. Answer me if you have any solution for this.

function open() {
    x = document.getElementById('s');
    x.style.background = "green";
}

function close() {
    document.getElementById('c').style.background = "red";
}
<!DOCTYPE html>
<html>
<head>
    <title>Events-code with me</title>
</head>
<body>
    <h1>Changing style</h1>
    <button id="s" onclick="document.getElementById('s').style.background='green'">Submit</button>
    <button id="c" onclick="close()">Clear</button>
</body>
</html>

4 Answers

close() is a method on the window object when you name your function as close and you called on click. the browser engine called the windows close() method, not your close method. A simple way to solve this is to rename your function.

function open() {
    x = document.getElementById('s');
    x.style.background = "green";
}

function closeX() {
    document.getElementById('c').style.background = "red";
}
<!DOCTYPE html>
<html>
<head>
    <title>Events-code with me</title>
</head>
<body>
    <h1>Changing style</h1>
    <button id="s" onclick="document.getElementById('s').style.background='green'">Submit</button>
    <button id="c" onclick="closeX()">Clear</button>
</body>
</html>

Check out this snippet:

<!DOCTYPE html>
<html>
<head>
    <title>Events-code with me</title>
</head>
<body>
    <h1>Changing style</h1>
    <button id="s" onclick="openX();">Submit</button>
    <button id="c" onclick="closeX();">Clear</button>
    <script type="text/javascript">
        function openX() {
            x = document.getElementById('s');
            x.style.background = "green";
        }

        function closeX() {
            document.getElementById('c').style.background = "red";
        }
    </script>
</body>
</html>

Actually when you use open(); and close();, it will call window.open(); and window.close();. In JavaScript, all global variables (like document)and functions(for eg alert()) belongs to window object (as window.documentand window.alert()).

To make those functions work, you must rename them, which I have done above.

The open() method is a default method of JS to opens a new browser window or a new tab, so change it with any other method name, for example

function openModal() {
    x = document.getElementById('s');
    x.style.background = "green";
}
<button id="s" onclick="openModal">Submit</button>

I'tried ur code with function call i'ts because open() and close() are an inbuilt function in javascript and don't forget to write ur js code in tag :)

Give an another function name instead of open and close

enter image description here

Related