1

I am trying to understand the concepts of core javascript. As we all know, We can call functions which are in global context for some event like this.

Html

<span class="name" onclick="clicked()">Name</span>

JavaScript

function clicked(){
   alert("span clicked");
}

But why we cannot call function i.e object method like following:

Html

<span class="name" onclick="nameobject.clicked()">Name</span>

javaScript

var nameobject = {
   clicked: function(){
     alert("Clicked");
   }
}

Is there something I am missing? Can someone help me on this?

2
  • You can call it but your js code should bind before html Commented Jan 23, 2017 at 11:26
  • can you reproduce the problem in stacksnippet ??? Commented Jan 23, 2017 at 11:27

3 Answers 3

1

You can call it but your js code should bind before html code You can check fiddle

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var nameobject = {
   clicked: function(){
     alert("Clicked");
   }
}
</script>
<span class="name" onclick="nameobject.clicked()">Name</span>

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

1 Comment

Sorry my bad, Without going through some minor error I posted my question here. We can call JS even after Html code, as object will be available globally. Thanks for helping out.
0

As far as I know, no such condition exists. It would work either way.

<span class="name" onclick="nameobject.click()">Name</span>
<span onclick="clicked()">Name2</span>
<script>
var nameobject = {
   click: function(){
     alert("span 1 Clicked");
   }
}
var clicked = function(){
  alert("span 2 clicked");
  }
</script>

1 Comment

Yeah, Correct. As I mentioned above, without analyzing error i posted question. It would work either way.
0

It works if you do NOT include your object declaration inside a $(document).ready() or window.onload function.

Example without window.onload:

var nameObject = {
   clicked: function(){
     alert("Clicked");
   }
}
<button onClick="nameObject.clicked()">
Click Me
</button>

Example with window.onload(throws error)

window.onload = function(){
  var nameObject = {
   clicked: function(){
     alert("Clicked");
   }
  }
};
<button onClick="nameObject.clicked()">
Click Me
</button>

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.