My JavaScript works as inline code but not as an include file. Any ideas why and how to fix it? - javascript

I have this form:
<form id="searchForm" class="search_field" method="get" action="">
...
...
</form>
Then this javascript:
var form = document.getElementById("searchForm");
form.doSearch1.onclick = searchPage;
form.doSearch2.onclick = searchPage;
form.showFeatureChoices.onclick = function( )
{
var cbs = form.featType;
for ( var c = 0; c < cbs.length; ++c )
{
cbs[c].checked = false;
}
document.getElementById("featuresDiv").style.display = "block";
}
function searchPage()
{
var form = document.getElementById("searchForm");
var searchText = form.searchBox.value.replace(/-/g,"");
form.searchBox.value = searchText;
if (searchText != "")
{
// collect features to search for:
var features = [ ];
var featTypes = form.featType;
for ( var f = 0; f < featTypes.length; ++f )
{
if ( featTypes[f].checked ) features.push( featTypes[f].value );
}
featureList = "'" + features.join("','") + "'";
searchMsg("Searching for '" + searchText + "' ...");
// startStatusUpdate(1000);
// findTask.execute(findParams, showResults);
var accord = dijit.byId("accordianContainer");
var resultsPane = dijit.byId("resultsPane");
accord.selectChild(resultsPane,true);
doSearch( searchText, featureList );
}
else
{
searchMsg("No search criteria entered, enter search text");
}
}
If I embed this code in same file as the <form..., it works fine.
If however, I have this js in another file and use as include file:
<script type="text/javascript" src="Views/JS/main.js"></script>
I get following error: "Object required" and it points to these lines:
form.doSearch1.onclick = searchPage;
form.doSearch2.onclick = searchPage;
Any ideas how to fix this?
Just a bit more info, the js code shown above in a file called main.js which is in a folder called JS and Js is in a folder called Views. The
Thanks a lot in advance

When you include the JavaScript code in the same page, where is it in relation to the form element? (Before or after it?) How about when you reference the external JavaScript file?
I'm guessing that in the former case the code is at the end of the file, while in the latter case the script reference tag is at the beginning?
If that's true then what's happening is this code is being executed before the DOM is ready:
var form = document.getElementById("searchForm");
form.doSearch1.onclick = searchPage;
form.doSearch2.onclick = searchPage;
If the form tag hasn't been rendered to the DOM yet then that first line won't find anything, and the subsequent lines will fail as a result. One approach is to put the script reference tags at the end, but that seems like a hack to me. Sometimes there are good reasons to keep them in the page header, not the least of which is cleaner management of the code in many cases. There are other ways to hold off on executing JavaScript code until the DOM is ready.

Related

define a herf link based on if/else scenario in JS file

So basically I'm a beginner in JavaScript and HTML and trying to play with functions call on JS that will edit my HTML file.
Now, I'm trying to redirect users to different pages based on their type.
I want to use "onload" function in order to determine the user type and edit the link according to the result.
HTML:
<body onload="what_user()">
<div id="result">zone</div>
</body>
JS file:
function what_user() {
var d = document.getElementById("result");
var user = ""; // get the user type
if (user == "") d.outerHTML = "" + "";
else d.outerHTML = "" + "";
}
I have some problems understanding how to call a function from HTML and use it on JS as well as return values.
Thanks in advance!!!
Don't play with elements as string. Create an element and put it where you want.
function what_user() {
var d = document.getElementById("result");
let a = document.createElement('a')
a.text = 'zone'
var user = ""; // get the user type
if (user == "") a.href = 'admin_index.html'
else {
a.href = 'admin_user.html'
}
d.parentNode.removeChild(d);
document.body.appendChild(a)
}
<body onload="what_user()">
<div id="result">zone</div>
</body>

write script without CDATA and Merge two scripts with same functions

I have these scripts which are almost the same but I'm unable to merge them into one..
also I want remove "CDATA" and keep the script functioning in blogger XML template
<script type='text/javascript'>// <![CDATA[
!function(){const e=document.querySelectorAll(".vplayer");for(var t=0;t<e.length;t++){console.log(e[t].dataset.v);const a="//i.ytimg.com/vi_webp/"+e[t].dataset.v+"/hqdefault.webp";var n=new Image;n.src=a,n.addEventListener("load",void e[t].appendChild(n)),e[t].addEventListener("click",function(){const e=document.createElement("iframe");e.setAttribute("allowfullscreen",""),e.setAttribute("frameborder","0"),e.setAttribute("src","//www.youtube.com/embed/"+this.dataset.v+"?rel=0&showinfo=0&autoplay=1&iv_load_policy=3&modestbranding=1&noCookie=false&origin=https%3A%2F%2Fwww.xotaku.com&widgetid=1"),this.innerHTML="",this.appendChild(e)})}}();// ]]></script>
and that the second
<script type='text/javascript'>// <![CDATA[
!function(){const e=document.querySelectorAll(".vplayerold");for(var t=0;t<e.length;t++){console.log(e[t].dataset.v);const a="//i.ytimg.com/vi/"+e[t].dataset.v+"/hqdefault.jpg";var n=new Image;n.src=a,n.addEventListener("load",void e[t].appendChild(n)),e[t].addEventListener("click",function(){const e=document.createElement("iframe");e.setAttribute("allowfullscreen",""),e.setAttribute("frameborder","0"),e.setAttribute("src","//www.youtube.com/embed/"+this.dataset.v+"?rel=0&showinfo=0&autoplay=1&iv_load_policy=3&modestbranding=1&noCookie=false&origin=https%3A%2F%2Fwww.xotaku.com&widgetid=1"),this.innerHTML="",this.appendChild(e)})}}();// ]]></script>
the scripts are the same and I dont want write the whole of it twice
I want this
const e = document.querySelectorAll(".vplayer");
to work with that
const a = "//i.ytimg.com/vi_webp/" + e[t].dataset.v + "/hqdefault.webp";
and this
const e = document.querySelectorAll(".vplayerold");
to work with that
const a="//i.ytimg.com/vi/"+e[t].dataset.v+"/hqdefault.jpg";
the rest of scripte work with both as well
I want remove "CDATA" and keep the script functioning in blogger XML template
That's not possible. It's pretty much required for valid XML unless you want to use escape sequences for <>'".
the scripts are the same and I dont want write the whole of it twice
Make that IEFE a named function declaration, give it parameters, call it twice with different arguments.
<script type="text/javascript">//<![CDATA[
function createPlayer(selector, makeUrl) {
const e = document.querySelectorAll(selector);
for (var t = 0; t < e.length; t++) {
console.log(e[t].dataset.v);
const a = makeUrl(e[t].dataset.v);
var n = new Image;
n.src = a;
n.addEventListener("load", void e[t].appendChild(n));
e[t].addEventListener("click", function() {
const e = document.createElement("iframe");
e.setAttribute("allowfullscreen", "");
e.setAttribute("frameborder", "0");
e.setAttribute("src", "//www.youtube.com/embed/" + this.dataset.v + "?rel=0&showinfo=0&autoplay=1&iv_load_policy=3&modestbranding=1&noCookie=false&origin=https%3A%2F%2Fwww.xotaku.com&widgetid=1");
this.innerHTML = "";
this.appendChild(e);
})
}
}
createPlayer(".vplayer", v => "//i.ytimg.com/vi_webp/" + v + "/hqdefault.webp");
createPlayer(".vplayerold", v => "//i.ytimg.com/vi/" + v + "/hqdefault.jpg");
//]]></script>
Merged example
You mean like this?
<script type='text/javascript'>// <![CDATA[
!function(){const e=document.querySelectorAll(".vplayer");for(var t=0;t<e.length;t++){console.log(e[t].dataset.v);const a="//i.ytimg.com/vi_webp/"+e[t].dataset.v+"/hqdefault.webp";var n=new Image;n.src=a,n.addEventListener("load",void e[t].appendChild(n)),e[t].addEventListener("click",function(){const e=document.createElement("iframe");e.setAttribute("allowfullscreen",""),e.setAttribute("frameborder","0"),e.setAttribute("src","//www.youtube.com/embed/"+this.dataset.v+"?rel=0&showinfo=0&autoplay=1&iv_load_policy=3&modestbranding=1&noCookie=false&origin=https%3A%2F%2Fwww.xotaku.com&widgetid=1"),this.innerHTML="",this.appendChild(e)})}}();
!function(){const e=document.querySelectorAll(".vplayerold");for(var t=0;t<e.length;t++){console.log(e[t].dataset.v);const a="//i.ytimg.com/vi/"+e[t].dataset.v+"/hqdefault.jpg";var n=new Image;n.src=a,n.addEventListener("load",void e[t].appendChild(n)),e[t].addEventListener("click",function(){const e=document.createElement("iframe");e.setAttribute("allowfullscreen",""),e.setAttribute("frameborder","0"),e.setAttribute("src","//www.youtube.com/embed/"+this.dataset.v+"?rel=0&showinfo=0&autoplay=1"),this.innerHTML="",this.appendChild(e)})}}();
// ]]>
</script>
Adding them in separate script tags should also work, depending what your backend allows you to do.

Cannot get the number of var using javascript

I have this certain problem where I cannot get the number value of 'currentStock' var data inside an HTML file using JavaScript. I have this on my HTML file in script tag:
By the way, due to the HTML being too large, and also it was not originally my script, but from a friend who was asking for some help on adding some features in it, I can't upload the whole script as it will be going to be too long. The whole HTML script has 14076 characters with 289 lines.
I have only studied java and not javascript with HTML, so I need help with this one.
<script>
window.onload = function() {
var goDown = document.getElementById('uniqueNav');
var goRight = document.querySelector('.clothesNav');
var goUp = document.querySelector('.shrink');
goDown.style.marginTop = "0px";
goRight.style.marginLeft = "5px";
goUp.style.height = "0px";
}
$('document').ready(function(){
var name = "Ombre Printed Shirt";
var price = "P499.00";
var initialStock = 0;
var currentStock = initialStock;
document.querySelector('#clothTitle').innerHTML = "" +name;
document.querySelector('#clothPrice').innerHTML = "Price: " +price;
document.querySelector('#PITitle').innerHTML = "" +name;
document.querySelector('#PIPrice').innerHTML = "Price: " +price;
document.querySelector('#currentStock').innerHTML = "CurrentStocks: " +currentStock;
}); //------------------------Change This Every Document ----------------------------//
</script>
then this in my JavaScript File:
var cStocks = document.getElementById('currentStock').data;
alert(typeof cStocks);
alert("Data in cStocks = " + cStocks);
if (!cStocks) {cStocks = 0; alert("cStocks, not a valid number");}
if ((cStocks <= 0) == true)
{
document.querySelector('.clothButton').style.display='none';
document.querySelector('.clothButtonDisabled').style.display='flex';
}
else
{
document.querySelector('.clothButton').style.display='flex';
document.querySelector('.clothButtonDisabled').style.display='none';
}
upon loading the page, the alert says thaat the data type is undefined. I don't know what's happening with my code. did I miss something?
By the way, I have JQuery on my HTML page. it says JQuery v3.3.1 as a version
It doesn't look to me like #currentStock will have a data attribute, or value attribute (which is for inputs), so of course the js returns undefined. Right now it looks like #currentStock is having the innerHTML set on the document.ready to Current Stocks: 0
You do have an accessible variable, currentStock, which is defined during document.ready. Why aren't you accessing it directly? It will have the numeric value in it already. All you can get from #currentStock is the html you generated on document.ready, and you'd have to parse the number out of it, when it's available in raw form in the js variable currentStock.

Insert javascript from an external script into javascript in the HTML

I have some JS from an external JS file that I want to insert inside of a JS function in the HTML file. I can not touch the JS script in the HTML file, so I am wondering if this method can be done.
Here is the JS I want to insert inside of the JS function in the HTML file.
// FIRST JS TO INSERT
if (OS == "mobile"){
killVideoPlayer();
}
// SECOND JS TO INSERT
if (OS == "mobile"){
loadHtmlFiveVideo();
if (!document.all){
flvPlayerLoaded = false;
}
}else {
loadVideoPlayer();
}
Then I want to insert it into here.
<script>
function mediaTypeCheck() {
if (bsiCompleteArray[arrayIndex].mediaType == "video") {
// INSERT FIRST JS HERE
document.getElementById("bsi-video-wrap").style.display = "block";
document.getElementById('pngBsi').style.display = "block";
document.getElementById("frame_photo").style.display = "none";
document.getElementById("relativeFrame").style.display = "block";
document.getElementById("buy-me-photo-button-bsi").style.display = "none";
// INSTER SECOND JS HERE
loadVideoPlayer();
}
if (bsiCompleteArray[arrayIndex].mediaType == "photo") {
killVideoPlayer();
document.getElementById("bsi-video-wrap").style.display = "none";
document.getElementById('pngBsi').style.display = "block";
document.getElementById("relativeFrame").style.display = "block";
document.getElementById("frame_photo").style.display = "block";
document.getElementById("buy-me-photo-button-bsi").style.display = "block";
if (!document.all){
flvPlayerLoaded = false;
}
}
}
</script>
Thank you!
In JavaScript, you can overwrite variables with new values at any time, including functions.
By the looks of it, you could replace the mediaTypeCheck function with one of your own that does what you need and then calls the original function.
E.g.
(function(){
// keep track of the original mediaTypeCheck
var old_function = mediaTypeCheck;
// overwrite mediaTypeCheck with your wrapper function
mediaTypeCheck = function() {
if ( conditions ) {
// do whatever you need to, then ...
}
return old_function();
};
})();
The above can be loaded from any script, so long as it happens after the mediaTypeCheck function is defined.
The easiest way for me in the past has been using server-side includes. Depending on your back end, you can set up a PHP or ASP page or whatever to respond with a mime type that mimics ".js".
I'm not a PHP guy, but you'd do something like this: (if my syntax is incorrect, please someone else fix it)
<?php
//adding this header will make your browser think that this is a real .js page
header( 'Content-Type: application/javascript' );
?>
//your normal javascript here
<script>
function mediaTypeCheck() {
if (bsiCompleteArray[arrayIndex].mediaType == "video") {
//here is where you would 'include' your first javascript page
<?php
require_once(dirname(__FILE__) . "/file.php");
?>
//now continue on with your normal javascript code
document.getElementById("bsi-video-wrap").style.display = "block";
document.getElementById('pngBsi').style.display = "block";
.......
You cannot insert JS inside JS. What you can do is insert another tag into the DOM and specify the SRC for the external JS file.
You can directly insert js file using $.getScript(url);
if you have script as text then you can create script tag.
var script = docuent.createElement('script');
script.innerText = text;
document.getElementsByTagName('head')[0].appendChild(script);
The issue in your case is that you cannot touch the script in the html, so I'll say that it cannot be done on the client side.
If you could at least touch the script tag (not the script itself), then you could add a custom type to manipulate it before it executes, for example:
<script type="WaitForInsert">
Your question looks some strange, but seems to be possible. Try my quick/dirty working code and implement your own situation:
$(document.body).ready(function loadBody(){
var testStr = test.toString();
var indexAcc = testStr.indexOf("{");
var part1 = testStr.substr(0, indexAcc + 1);
var part2 = testStr.substr(indexAcc + 1, testStr.length - indexAcc - 2);
var split = part2.split(";");
split.pop();
split.splice(0,0, "alert('a')");
split.splice(split.length -1, 0, "alert('d')");
var newStr = part1 + split.join(";") + ";" + "}";
$.globalEval(newStr);
test();
}
function test(){
alert('b');
alert('c');
alert('e');
}

Get the element below the ready-function code, in jQuery?

For example:
<script>
$(document).ready( function() {
alert( $(this).getBelowElementToThisScript('form').id );
});
</script>
<form id="IamTheNext"></form>
<form id="Iamnot"></form>
This code should show this message: IamTheNext
In addition, the solution needs to work with this example too:
<script src="getbelowelement.js"></script>
<form id="IamTheNext"></form>
<form id="Iamnot"></form>
Thanks
Try this:
var form = $('script[src="getbelowelement.js"]').next();
But I would suggest using the forms id:
var form = $('#IamTheNext');
You could also try giving the script tag an id.
This kind of approach is dangerous; script should never depend that much on where it is in the page.
That said, the following works in Firefox and Chrome and should work in the major browsers (use at your own risk).
See it in action at jsBin. Both <script> ... and <script src="..."> approaches are shown in the same page.
$(document).ready( function () {
invocationsOfThis = (typeof invocationsOfThis == 'number') ? invocationsOfThis + 1 : 1;
var scriptTags = document.getElementsByTagName ('script');
var thisScriptTag = null;
//--- Search scripts for scripts of this type.
for (var foundCnt = 0, J = 0, L = scriptTags.length; J < L; ++J)
{
/*--- Since the script can be either inline or included, search
both the script text and the script src link for our unique
identifier.
*/
var thisTag = scriptTags[J];
var scriptCode = thisTag.innerText || thisTag.textContent;
var scriptSrc = thisTag.src;
//--- IMPORTANT, change pastebin.com to the filename that you use.
if (/invocationsOfThis/i.test (scriptCode) || /pastebin.com/i.test (scriptSrc))
{
//--- Found a copy of this script; is it the right one, based on invocation cnt?
foundCnt++;
if (foundCnt == invocationsOfThis) {
thisScriptTag = thisTag;
break;
}
}
}
if (thisScriptTag) {
//--- Get the target node.
var nextForm = $(thisScriptTag).next ('form');
var nextFormId = nextForm.attr ('id');
//--- Act on the target node. Here we notify the user
nextForm.text ('This is form: "' + nextFormId + '".');
}
} );

Categories