page javascript onload can only use one function in a var? - javascript

I've written a basic page in html, putting this in the head:
<script type="text/javascript" src="scripts/main.js"></script>
and the contents of my main.js are extremely simple:
var main = {
onload : function() {
alert("HI");
}
showSurprise : function() {
alert("HI");
}
}
window.onload = main.onload;
however, it seems that having these two functions exist at the same time causes neither of them to work, whether I set window.onload to the onload or the showSurprise function. If I delete one of them, it works fine.

You have syntax error. It should be:
var main = {
onload: function() {
alert("HI");
},
showSurprise: function() {
alert("HI");
}
};

I hope this is what you are looking for
var main = {
onload: function() {
alert("HI");
},
showSurprise: function() {
alert("HI");
}
};
window.onload = main.onload();
You should pass it as a function.

Related

Two Scripts are Conflicting - One that is second in order works - looking for solution

Here are the two scripts in question. Only the second will run. I can reverse them and whichever one is second will run. How can I resolve this conflict?
SCRIPT 1
<script>
function init() {
var vidDefer = document.getElementsByTagName('iframe');
for (var i=0; i<vidDefer.length; i++) {
if(vidDefer[i].getAttribute('data-src')) {
vidDefer[i].setAttribute('src',vidDefer[i].getAttribute('data-src'));
} } }
window.onload = init;
</script>
SCRIPT 2
<script>
window.onload = function() {
richSnippetReviewsWidgets({
store: "www-majorsafety-com",
primaryClr: "#f47e27",
widgetName: "floating-widget",
numReviews: 40,
floatPosition: "right",
contentMode: "company;third-party",
hideDates: false
});
};
</script>
window.addEventListener('load', function(){ ... });
Add an event listener, otherwise onload = does a complete replace of any previous set to that single property.
You can only have one function set in window.onload for the page.
To work around this, just use addEventListener.
The first script becomes:
<script>
function init() {
var vidDefer = document.getElementsByTagName('iframe');
for (var i=0; i<vidDefer.length; i++) {
if(vidDefer[i].getAttribute('data-src')) {
vidDefer[i].setAttribute('src',vidDefer[i].getAttribute('data-src'));
} } }
window.addEventListener('load', init)
</script>
The second script becomes:
<script>
window.addEventListener('load', function() {
richSnippetReviewsWidgets({
store: "www-majorsafety-com",
primaryClr: "#f47e27",
widgetName: "floating-widget",
numReviews: 40,
floatPosition: "right",
contentMode: "company;third-party",
hideDates: false
});
})
</script>

Passing data to a javascript file after loading fails

I have the following in my html
<html>
<body>
<script type="text/javascript">
var hccid=98964571;
function add_chatinline(){
var nt=document.createElement("script");
nt.async=true;
nt.src="http://localhost/ll.js";
var ct=document.getElementsByTagName("script")[0];
ct.parentNode.insertBefore(nt,ct);
console.log("state is ", SORCHAT)//SORCHAT is not defined
}
add_chatinline();
</script>
</body>
</html>
On the ll.js i have
var SORCHAT = SORCHAT || (function () {
return {
init: function (Args) {
console.log("hash is ", Args)
},
};
}());
But now am getting an error of SORCHAT is not defined.
By adding window.onload that is
<script>
window.onload = function(){
SORCHAT.init(12736474676); //this works
}
</script>
But whenever i include another javascript file with window.onload function the SORCHAT.init is not executed.
What am i missing.
You are probably overwriting the window.onload when using it multiple times. You can prevent that with the help of the addEventListener-function.
window.onload = function () {
console.log('onload #1');
}
window.onload = function () { // This replaces the first onload (#1)
console.log('onload #2');
}
window.addEventListener('load', function () {
console.log('onload #A');
});
window.addEventListener('load', function () {
console.log('onload #B');
});

jquery/javascript function work in the firebug console but not on page load

Long story short i need to edit a textarea after it was created by a wordpress plugin, i can set the id and default value, but i can't set events or anything else, i want the default value to disappear after the user clicks to enter the phone number.
I have tried several ways of doing this without luck, some are:
<script type="text/javascript">
$(document).ready(function(){
// Your code goes here
function clearOnInitialFocus ("telid01") {
var clearedOnce = false;
document.getElementById("telid01").onfocus = (function () {
if (clearedOnce == false) {
this.value = '';
clearedOnce = true;
}
})
}
window.onload = function() { clearOnInitialFocus('telid01');}
});
</script>
Also tried
<script type="text/javascript">
$(document).ready(function(){
document.getElementById('telid01').addEventListener('focus', function() {
this.value = "";
});
});
</script>
this works in the console but not on page load:
document.getElementById('telid01').addEventListener('focus', function() {
this.value = "";
Since you're using jQuery, you may as well use jQuery's event binding, like so:
$(document).ready(function(){
var clearedOnce = false;
$(this).on('focus', '#telid01', function () {
if (!clearedOnce) {
$(this).val('');
clearedOnce = true;
}
});
});
Edit: If you attach the event to 'document' then pass the id as a selector to on() it should work, and should be able to attach the event even without the field existing on the page yet. See: http://api.jquery.com/on/
You are using function parameters in a strange way.
I've tried the following code that is based on yours and it works fine.
<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// Your code goes here
var clearedOnce = false;
document.getElementById("myTest").onfocus =
function () {
if (clearedOnce == false) {
this.value = '';
clearedOnce = true;
}
};
});
</script>
</head>
<body>
<input id="myTest" value="placeholder" />
</body>
</html>

Calling Javascript Functions by name

If I have an element on the page like this ...
<span data-function="DoSomething">Click</span>
... and i put this in my page header ...
$(document).ready(function()
{
$('[data-function]').each(function()
{
var fName = $(this).attr('data-function');
$(this).click(fName);
});
});
... what goes in place of the comment produce the desired effect of executing the function called "DoSomething".
Note:
I no the code above wont work, my question is how to make this work (translate 'DoSomething' in to DoSomething();)
Any ideas guys?
The functions should be available. Try putting them in an Object, like this:
$(document).ready(function()
{
var fns = {
DoSomething: function() {/* ... */},
DoAnotherthing: function() {/* ... */}
};
$('[data-function]').each(function()
{
var fName = $(this).attr('data-function');
$(this).click(fns[fName]);
});
});
Here's a jsfiddle, demonstrating a way to keep everything local to one namespace and assigning handlers based on the data attribute of elements.
Try calling function with window object -
$(document).ready(function() {
$('[data-function]').each(function() {
var fName = $(this).attr('data-function');
if (typeof (window[fName]) === "function") {
$(this).click(window[fName]);
}
});
}
You can use something like
$(this).click(window[fName]);
Where window would be replaced by the appropriate expression if the function DoSomething is not defined in the global scope.
Maybe a little bit clean way:
http://jsfiddle.net/whsPG/
var myfuncs = {
alert : function() {
alert("An Alert");
},
changeName: function(obj) {
$(obj).text('Other Text');
}
};
$('[data-function]').on('click', function()
{
value = $(this).data('function');
if (myfuncs.hasOwnProperty(value)) {
myfuncs[value](this);
}
});
​

Use objects method as callback

I've got another JavaScript/jQuery-Problem. A minimal example could be this: I've got a div, and want some JavaScript executed, when the mouse enters. But for some reasons (= in reality, there a many divs, and for each data needs to be kept) I want to use a object as handler for the callback. Here's a small example:
function handler($thediv)
{
this.somedata = 8;
$thediv.mouseenter(function() { this.callback(); });
}
handler.prototype.callback = function()
{
alert(somedata);
}
An object is created when the document is loaded:
$(document).ready( function() {
new handler($("div"));
});
Nothing happens - except that the constructor is executed. I've tried and searched for hours now, but I can't fix this... probably too trivial?
Edit: A complete example.
<html>
<script type="text/javascript" src="jquery-1.6.js"></script>
</head>
<body>
<div>
blah blahasdasdadsssssssssssssss
asddddddddddddddddddddddddddd
</div>
</body>
<script type="text/javascript">
$(document).ready(function() {
new handler($("div"));
});
function handler($thediv)
{
this.somedata = 8;
$thediv.mouseenter(this.callback);
}
handler.prototype.callback = function()
{
alert(somedata);
}
</script>
</html>
The biggest issue here is the use of this in various contexts. Within the mouseenter function, this refers to div, not the object.
This should work:
http://jsfiddle.net/Nx5c7/
function handler($thediv)
{
this.somedata = 8;
this.theID=$thediv.attr("id");
var obj=this;
$thediv.mouseenter(function() {
obj.callback();
});
}
handler.prototype.callback = function()
{
alert(this.theID + " : " + this.somedata);
}

Categories