0

Why doesn't this simple code work?

<div onClick="myFunction()"></div>
$(document).ready(function(){
    function myFunction(){
       alert("sss");
    }
})

The JS file is external and it's called in the head of my HTML page. The jQuery library is added before that.

2 Answers 2

2

It doesn't work as functions called from the on* event attributes need to be within scope of the window. Your code places the function within the jQuery document.ready handler instead. Try this:

function myFunction() {
  alert("sss");
}
<div onClick="myFunction()">Click me</div>

You should note though, that using on* event attributes is considered outdated for this reason, amongst many. You should instead use unobtrusive JS code to attach your event handlers, either in native JS:

document.querySelector('div').addEventListener('click', function() {
  alert("sss");
});
<div>Click me</div>

Or jQuery, as you seem to be using it already:

$(function() {
  $('div').on('click', function() {
    alert("sss");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Click me</div>

Sign up to request clarification or add additional context in comments.

Comments

0

First Go and read tutorials of html and Jquery at some tutorial websites like This or thisone.

and answer to your code is

HTML

<button onclick="myFunction()">Click me</button>

Javascript

function myFunction() {
    alert('Hello');
} 

Assuming you included JQuery libraries.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.