I am trying something like this
<div onclick="check_update('personal_details') ; showUser(2)">Click me </div>
but only check_update('personal_details') is getting called . I want to execute two separate functions at the same time when DIV is clicked. Any help will be great for me as I am still in a learning phase. Thanks in advance.
You can't execute two functions at the same time. JavaScript in a web browser is single threaded.
The code you have will execute the functions sequentially, providing that the first one doesn't throw an exception and terminate the execution.
If it does throw an exception then you should try to resolve that. As a brute force hack:
try {
check_update('personal_details') ;
} catch (e) {
alert("Oh no! An exception! " + e);
}
showUser(2);
… but preventing the error in the first place is, obviously, a better solution!
You're question is tagged as jQuery, so I'm going to assume you're using it. In that case, you shouldn't be using the onclick attribute at all. This would be the correct way to write the code from a jQuery perspective:
<div id="yourId">Click me</div>
<script type="text/javascript">
$('#yourId').click(function(e) {
e.preventDefault();
check_update('personal_details');
showUser(2);
});
</script>
Use a function within a closure. Replace otherFunction with the name of the second function you'd like to call and everything should work as expected.
<div onclick="(function(){check_update('personal_details'); otherFunction(); })()">Click me </div>
Related
I dont know a whole lot about javascript and i was wondering if this script would run or do i need to put the "if statement" inside some kind of onPageLoad function to run this? Please help.
<script>
if (time<20)
{
alert("Hello World!");
}
</script>
Sure it would run -- but it would depend on something else having run first so that time has a value.
For example, this would work (even though it's bad practice because it sets a property on window):
<script>
time = 10;
</script>
<script>
if (time<20)
{
alert("Hello World!");
}
</script>
You would also find it impossible to guarantee that any variables you need for temporary processing are kept out of the reach of other scripts. To overcome this limitation, you can (and except in the most trivial of sites, should) wrap the code inside an anonymous function that is invoked on the spot:
<script>
(function() {
// your code here
})();
</script>
If you want to access DOM Elements you have to put the script tag at the end of the page. Or you use something like onload of the body tag (or an equivalent funciton in JS framework)
It would run, realize time is undefined, generate an error and halt operations from that point on.
If "time" is seted on server side, so, you may write onload property body dinamically like this:
<body onload="functionName(<?php echo()?>)">
and then:
<script type="text/javascript">
function functionName(time) {
if(time < 30) { ... }
}
</script>
At one line of my code I have something like that:
...
while(!$scope.isMyTurn(privilege)){}
I will run next line of codes
However as usual it blocks my browser. I have to wait until get true to run next line of codes. I don't want to block my browser and other functionalities should work because(some of other fired events will change the situation of my turn) User should continue whatever he does.
This is for refreshing a graphic until my turn is come.
You should be doing it something like :
$scope.$watch("isMyTurn(privilege)",function(val){
if(val){
//I will run next line of codes
}
});
instead of what you are attempting to do..
Note that in this scenario, privilege should also be a scope variable something like
$scope.privilege
If you dont want it to be a scope variable just dont pass it as an argument. but directly access it inside the function..
Hope this helps..
Consider using the $scope.$watch function.
Look under ($watch):
http://docs.angularjs.org/api/ng.$rootScope.Scope
I don't know about angularJS but in normal JavaScript you could use setTimeout
function whenReady()
{
if ($scope.isMyTurn(privilege)){
I will run next line of codes
}
else
{
window.setTimeout(whenReady, 1000);
}
}
window.setTimeout(whenReady, 1000);
In my javascript code ( which is too long , so i can`t put it here ), functions are calling more than once , like suppose :
$("#button").bind({ click : Call }); // bind the Call with button click event
function Call()
{
alert("This message shows me more than once when i clicked the button");
}
if this alert message shows me more than once it means function Call() is calling more than once. Can anybody guess or tell me what's going on in my code? (Please don't ask me for code)
Works for me: http://jsfiddle.net/aC8Bm/
I'm guessing that you are binding more than once somewhere.
Also, I'd recommend either returning false from the Call function, or stopping event propagation.
One more thing: avoid naming functions with an uppercase -- that's reserved for constructor functions by convention.
You're hooking the event handler to the button the number of times 'Call' is being called. Do you have this code in something like a template or partial file?
Instead of doing this inside any function:
$("#button").bind({ click : Call });
Place the following somewhere outside:
$("#button").live("click", Call);
It will bind once for all existing and ever added #button
I'm finding that with asynchronous callbacks I'm needing to write a try/catch for each callback function. It seems a bit error prone is there a method or technique whereby I can implement a single top level try/catch that catches everything? If not is the technique that I'm using considered good practice or is there a better way to do things?
There is two ways of doing this:
Set the window's onerror attribute
called with three arguments (message, url, lineNumber)
returning true(!) prevents the default error handling (making this something like a catch-all)
Add an error event listener to window
called with an Error event e as its sole argument
Calling e.preventDefault() prevents default error handling
If not is the technique that I'm using considered good practice or is there a better way to do things?
Due to the dynamic nature of JavaScript, try/catch is very slow. There's almost always better ways, for example: check if something exists before calling a method on it.
// bad
try {
document.getElementById('foo').focus();
} catch(e) {
alert('foo not found');
}
//good
var el = document.getElementById('foo');
if (el) {
el.focus();
} else {
alert('foo not found');
}
For your specific situation, please show some of your code; maybe in a separate question.
Nope, don't do it catch-all, that almost always results in problems (because you can't differentiate between exceptions very well).
It probably isn't a good idea to depend on a global catch all, but it isn't a bad idea to have one (in the case where an error is thrown where you might not expect). This way you can handle uncaught errors the way you would like to.
Using jQuery:
$(window).error(function (msg, url, line) {
//do something
});
Not sure the best way to phrase the question, but suppose you are using jQuery to setup various things like so:
<script>
function doSecond(){
alert("Hi");
}
function dofirst(){
var x = asdasd;
}
$(dofirst);
$(doSecond);
</script>
So, imagine that dofirst and dosecond are completely independent. If dofirst throws an exception, which of course it will, then doSecond will never fire. I understand why this happens, but I'm wondering if there is a way of getting around this without having to wrap EVERY kind of jQuery handler that I want to set up in a try catch. E.g., I'd rather not do:
try{
$(doFirst);
}
catch{
//maybe log here?
}
try{
$(doSecond);
}
catch{
//maybe log here?
}
Now, if you're wondering why I want to do this? Well, take for example the code on the page you're looking at right now:
<script type="text/javascript">
$(function() {
$('#title').focus(function() { $('#how-to-tag').hide(); $('#how-to-format').hide(); $('#how-to-title').fadeIn('slow'); });
$('#wmd-input').focus(function() { $('#how-to-tag').hide(); $('#how-to-format').fadeIn('slow'); $('#how-to-title').hide(); });
$('#tagnames').focus(function() { $('#how-to-tag').fadeIn('slow'); $('#how-to-format').hide(); $('#how-to-title').hide(); });
});
</script>
Is it really necessary to have certain dom elements fade out when you click on them? No. But if you make a mistake in that function, then quite possibly other javascript that you really, really do need to run may never get setup.
A couple of ways to ensure things run independently of each other:
As you said, try/catch around each
Call each in a setTimeout (or
whatever the jQuery syntactic sugar
is for that)
Separate into different <script>
blocks
Obviously not ever throwing an exception is a ridiculous suggestion. Especially in the world of many browsers/versions/servers up/servers down. There are so many ways of website JS to break it's hard to find a site of any size which doesn't throw an exception of some type (on console examination).
You could create a simple wrapper (or extend existing jQuery methods)
function safeonload(fn){
$(function(){
try{
fn();
}catch{
//log?
}
});
}
safeonload(doFirst);
safeonload(doSecond);