Firebug doesn’t display my javascript? can't find the error - javascript

well I want to debug some script with Firebug, (cause I can't see anything in the browser window) but when I click the script tab in Firefox it gives me the error message:
If tags have a "type" attribute, it should equal "text/javascript" or "application/javascript". Also scripts must be parsable (syntactically correct).
What am I doing wrong?
Here's my code:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script src="jquery-1.7.1.js"></script>
<script type="text/javascript">
$(function() {
/* fix: “close” the value of i inside createFunction, so it won't change */
var createFunction = function(i) {
return function() { alert(i); };
};
for (var i=0; i<5; i++) {
$('p').appendTo('body').on("click", createFunction(i));
}
})();
</script>
</body>
</html>

You must leave out the last parenthesis, I guess the code should run on dom ready?
<script type="text/javascript">
$(function() {
/* fix: “close” the value of i inside createFunction, so it won't change */
var createFunction = function(i) {
return function() { alert(i); };
};
for (var i=0; i<5; i++) {
$('<p>').appendTo('body').on("click", createFunction(i));
}
});
</script>
See here for how to make code running on dom load with jquery.

Remove parenthesis after }):
$(function() {
/* fix: “close” the value of i inside createFunction, so it won't change */
var createFunction = function(i) {
return function() { alert(i); };
};
for (var i=0; i<5; i++) {
$('p').appendTo('body').on("click", createFunction(i));
}
}); //here is the modification

In my Case I have opened firebug in other tab, So it was showing me this error.
Solution : I have closed one tab and refreshed the page. and it was working :)

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>

Non-independence of two javascript scripts

He Guys,
I have two scripts that work fine separately. One is for loading images and one is for loading Youtube iframe embeds.
However they don't seem to work together. Could you help out?
<iframe width="560" height="315" frameborder="0" data-src="https://www.youtube.com/embed/fKnbOJ4NAvS" src=""></iframe>
<a rel="nofollow" target="_blank" href="https://plus.google.com/share?url=https%3A%2F%2Fwww.domain.com"><img src="data:image/png;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" data-src="googleplus.png"></a>
<script>
function init() {
var imgDefer = document.getElementsByTagName('img');
for (var i=0; i<imgDefer.length; i++) {
if(imgDefer[i].getAttribute('data-src')) {
imgDefer[i].setAttribute('src',imgDefer[i].getAttribute('data-src'));
} } }
window.onload = init;
</script>
<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>
You have made a couple of invalid assumptions.
Firstly, all scripts occupy the same global name space. Multiple <script>...</script> tags are not independent, therefore.
<script>
//script 1
</script>
<script>
//script 2
</script>
is equivalent to :
<script>
//script 1
//script 2
</script>
Secondly, repeated assignments of functions to window.onload are not cumulative. With window.onload = init followed by a second window.onload = init, the second assignment will override the first.
Now you should understand that your second script nullifies the first.
To fix, you could give the two functions unique names, and call them from a single (anonymous) window.onload handler :
<script>
function init_1() {
var imgElements = document.getElementsByTagName('img');
for (var i=0; i<imgElements.length; i++) {
if(imgElements[i].getAttribute('data-src')) {
imgElements[i].setAttribute('src', imgElements[i].getAttribute('data-src'));
}
}
}
function init_2() {
var vidElements = document.getElementsByTagName('iframe');
for (var i=0; i<vidElements.length; i++) {
if(vidElements[i].getAttribute('data-src')) {
vidElements[i].setAttribute('src', vidElements[i].getAttribute('data-src'));
}
}
}
window.onload = function() {
init_1();
init_2();
};
</script>
You could alternatively omit init_1() and init_2(), and write everything direcly inside an anonymous window.onload handler :
<script>
window.onload = function() {
var imgElements = document.getElementsByTagName('img');
var vidElements = document.getElementsByTagName('iframe');
var i;
for (i=0; i<imgElements.length; i++) {
if(imgElements[i].getAttribute('data-src')) {
imgElements[i].setAttribute('src', imgElements[i].getAttribute('data-src'));
}
}
for (i=0; i<vidElements.length; i++) {
if(vidElements[i].getAttribute('data-src')) {
vidElements[i].setAttribute('src', vidElements[i].getAttribute('data-src'));
}
}
};
</script>
It is perfectly OK to reuse the variable i in this way.
You will notice that I renamed you variables to avoid "Defer", which has a very specific meaning in JavaScript.

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>

How to collect all script tags of HTML page in a variable

I would like to collect all the <script> ....</script> code section present in the HTML page in some variable.
What should be the simpler way to do this, Any idea how it can be retrieved using JavaScript.??
Any help will be greatly appreciated.
To get a list of scripts you can use
document.getElementsByTagName("script"); by tag
document.scripts; Built-in collection
document.querySelectorAll("script"); by selector
$("script") jQuery by selector
var scripts = document.getElementsByTagName("script");
for (var i = 0; i < scripts.length; i++) {
if (scripts[i].src) console.log(i, scripts[i].src)
else console.log(i, scripts[i].innerHTML)
}
// To get the content of the external script
// - I use jQuery here - only works if CORS is allowing it
// find the first script from google
var url = $("script[src*='googleapis']")[0].src;
$.get(url,function(data) { // get the source
console.log(data.split("|")[0]); // show version info
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
console.log("Inline script");
</script>
<script>
function bla() {
console.log("Other inline script");
}
</script>
The simplest way is probably document.scripts
You would do:
var scripts = document.getElementsByTagName( 'script' );
Now scripts is a NodeList (like an array), and you can access each one using scripts[0], scripts[1] and so on.
try this
var scripts = document.getElementsByTagName("script");
Without jQuery :
var scripts = document.getElementsByTagName("script");
With jQuery :
var scripts = $("script");
Here you go --
(function () {
'use strict';
let logscript = function () {
let js = document.scripts;
for (let i = 0; i < js.length; i++) {
if (js[i].src) {
console.log(i, js[i].src);
} else {
console.log(i, js[i].innerHTML);
}
}
};
if (document.readyState === 'complete') {
logscript();
} else {
window.addEventListener('load', logscript);
}
})();

Why doesn't function.apply() work across document boundaries in IE?

I'm seeing some strange behavior in IE trying to call functions in another page via function.apply().
Here's a simple test case:
test1.html:
<HTML>
<HEAD>
<script language="javascript" type="text/javascript">
var opened = null;
function applyNone() {
opened.testFunc.apply(opened);
}
function applyArgs() {
opened.testFunc.apply(opened, ["applied array"]);
}
function call() {
opened.testFunc("called directly");
}
function remoteApply() {
opened.testApply(["used remote apply"]);
}
function remoteApplyCopy() {
opened.testApplyCopy(["used remote apply copy"]);
}
function openPopup() {
opened = window.open("test2.html", "_blank");
}
</script>
</HEAD>
<BODY>
OPEN
<hr>
applyNone
applyArgs
call
remoteApply
remoteApplyCopy
</BODY>
</HTML>
test2.html:
<HTML>
<HEAD>
<script language="javascript" type="text/javascript">
function testApply(args) {
testFunc.apply(this, args);
}
function testApplyCopy(args) {
var a = [];
for(var i = 0; i < args.length; i++) {
a.push(args[i]);
}
testFunc.apply(this, a);
}
function testFunc() {
var s = "Got: ";
for(var i = 0; i < arguments.length; i++) {
s += arguments[i] + " ";
}
document.getElementById("output").innerHTML += s + "<BR>";
}
</script>
</HEAD>
<BODY>
Hi there
<div id="output"/>
</BODY>
</HTML>
In firefox and chrome all methods work properly.
In IE (tested in 6, 7, and 8) all but the applyArgs() and remoteApply() methods work as expected.
applyArgs() gives a "JScript object expected" error when it tries calling apply (test1.html line 11).
remoteApply() gives the same "JScript object expected" error when it tries calling apply (test2.html line 5).
Problem is, I need to be able to use apply(). I can get around the issue by doing something like the remoteApplyCopy() mechanism, but I'm trying to avoid that. Why doesn't apply() just work?
You need to have the arrays created in the other window, because each window has its own Array constructor. I think this will work.
Add this function to test2.html:
function getEmptyArray() {
return new Array();
}
And this function to test1.html:
Array.prototype.cloneToRemote = function (win) {
var newArray = win.getEmptyArray();
for (var i = 0; i < this.length; i++)
{
newArray.push(this[i]);
}
return newArray;
}
Then do this:
function applyArgs() {
opened.testFunc.apply(opened, ["applied array"].cloneToRemote(opened));
}
Note, it seems like you should be able to do
var newArray = new win.Array();
within the test1.html cloneToRemote() function, but I couldn't make that work. If you could do that, you could get rid of the new getEmptyArray() function in test2.html.
I have no idea why this works, but I was playing around with your code and stumbled across one solution... put test2's functions inside of test1 and it works:
<HTML>
<HEAD>
<script language="javascript" type="text/javascript">
var opened = null;
function applyArgs() {
testFunc.apply(opened, ["applied array"]);
}
function openPopup() {
opened = window.open("test2.html", "_blank");
}
function testFunc() {
var s = "Got: ";
for(var i = 0; i < arguments.length; i++) {
s += arguments[i] + " ";
}
this.document.getElementById("output").innerHTML += s + "<BR>";
}
</script>
</HEAD>
<BODY>
OPEN
<hr>
applyArgs
</BODY>
</HTML>
I'll let you know if I can figure out any more (IE is weird like that). Like I said, I was just toying with the code.
If you change test2.html testApply() function as follows:
function testApply() {
testFunc.apply(this, arguments);
}
remoteApply() works. But, applyArgs() still failed.
"...
applyArgs() gives a "JScript object expected" error when it tries calling apply (test1.html line 11).
remoteApply() gives the same "JScript object expected" error when it tries calling apply (test2.html line 5).
..."
Which exact object is not "JScript object" as "expected" ?
(hint: use debugger)
--DBJ

Categories