Change Array.prototype in ecmascript (javascript) - javascript

I am working on an app using node_webkit combining HTML, CSS and JS. In one part of my app I want to update the Array.prototype so that I can access the last element of an array easily. The code for that is:
if (!Array.prototype.last){
Array.prototype.last = function(){
return this[this.length - 1];
};
}
If I run only the js-file that works fine and as expected. If I include that js-file into an HTML document it seems that the prototype of the array stays unchanged and I get the error:
data.last is not a function
Do I have to change something so that I can run my code normally from an HTML file or does that not work at all and I have to take the long way around and access each array with array[array.length - 1]?
The HTML code I use to include the script is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../CSS/Cocktails.css">
<title>Cocktails</title>
<script type="text/javascript" src="../JavaScript/Cocktail.js"></script>
</head>
<body>
/* some elements, that don't use the script yet */
</body>
</html>

It sounds like you're not calling the function, you'd want to call it like data.last() where data is some array that you've declared. Here's a JSFiddle of it in action.

In ES5 you need to use defineProperties in order to modify the Array prototype in an enumberable way:
Following should work,
Object.defineProperties(Array.prototype,
{ last: { value: function() { return this[this.length - 1]; } } });
More information at:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties

Related

Having issues using js to randomly reassign a css variable

I'm working on a part of a page that should load a random image from a folder every fraction of a second for a rapid shuffle. I've gotten it to get the file name and randomly set a style for it. Problem is, not at all how I was intending to do so. I want to set the css variable "--background-images" in my stylesheet, however all it seems to be doing upon manually running the function in console is adjust the html doc like so:
<html lang="en" style="--background-images\::url(\.\.\/\.\.\/rsrc\/acct-crt-page-images\/acct-crt-street-mural-16\.png);"><head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Account - Page 37</title>
<script src="../scripts/script.js"></script>
<link rel="stylesheet" href="../styles/account-creation-style.css" type="text/css">
</head>
Obviously this isn't what I was aiming to change--and beyond that I have no idea what that url it inserted is as it looks like a nightmare. I'm aiming to replace only the line in the css file. This is my js code:
// Load the root CSS variables
const style_root = document.querySelector(':root')
function random_image() {
// Get a random index postion of the images array
array_index = Math.floor(Math.random() * 19)++;
// Change the --background-images css variable based on the random index
style_root.style.setProperty(`--background-images`, `url(../../rsrc/acct-crt-page-images/acct-crt-street-mural-${array_index}.png)`);
}
I don't really know where to start or what is happening here now--I've been working with this aspect of the website for almost a week, and I was getting close but this roadblock has had me for 2-3 days.
I'm attempting to change a line of css, but instead I've gotten a weird and confusing line that doesn't function in html.

external .js variable coming back undefined?

I am trying to get an external .js variable into my index.html however the variable just comes back undefined. It works if the variable is in the HTML file but not when I call it from an outside .js file it just reads undefined ?
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="assets/css/main.css" />
<title>LoginSystem</title>
<script src="../server.js"></script>
</head>
<body>
<div id="display"></div>
<script>
var t = setInterval(function() {
// you can change `random` to any variable you want to be displayed
document.getElementById("display").innerHTML = random;
}, 500);
</script>
</body>
and the javascript file
var random = Math.random();
any help would be greatly appreciated thank you.
I can't explain why you're getting undefined; however, Since you set random in a variable outside of the scope of the function passed into setInterval, it will always display the same random number. You need to set random inside the function passed to setInterval if you want a new random number to show up.
server.js
function getRandomNumber() {
return Math.random();
}
index.html
var t = setInterval(function() {
document.getElementById("display").innerHTML = getRandomNumber();
}, 500);
Demo
https://repl.it/#AnonymousSB/RemarkableBowedNagware
i think you may be looking in the wrong directory for your server.js see this line:
<script src="../server.js"></script>
Make sure the file path is correct, if your index and server.js are in the same fodler it should be:
<script src="./server.js"></script>
I have tested the same code and it works perfectly for me.
Hope this helps.
Youu external javascript file path isn't correct. Replace ../server.js with /server.js

HTML equivalent of PHP include for JavaScript parts

I'm looking for a Javascript equivalent of a technique I've been using in PHP. That is, to place even the most basic page setup:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
...in a php file like 'doc_start.php' and then start every page in my site with...
<?php require_once('/path/to/doc_start.php); ?>
Now I need to begin a project that's strictly HTML and JS (no PHP) and want a similar way to avoid duplicating basic, common HTML elements. Obviously, I want to do more than this very basic stuff, like import JQuery in every page, link to a common stylesheet, etc. Again, all easy in PHP, but I'm still kind of a newbie in JS.
I've read about HTML5 includes, but can't seem to find anything that addresses what I want to do
In order to import other pages into your current document, you need to use a link tag.
For example....
<head>
<link rel="import" href="/path/to/imports/stuff.html">
</head>
This will allow you to reference other html, css or javascript documents into your page without copying and pasting the same code within each page.
https://www.w3schools.com/html/html_links.asp
Javascript and PHP are different languages for very different purposes. But assuming you have some element you don't want to repeat some elements one solution is the following:
Save the HTML elements that you don't want to keep repeating as a string. Then use the .innerHTML property to add elements.
The .innerHTML property stores the mark up of an element as a string.
For example, if we have the following <div>:
<div class="example"> <br> Hello there this is a test! </div>
...and we use .innerHTML:
console.log(document.querySelector(".example").innerHTML);
It will output "<br> Hello there this is a test!".
We can add to the .innerHTML using the += operator. So if you want to add something inside the body it's as simple as:
var something = "some HTML";
document.body.innerHTML += something;
Hope this was what you were looking for!

Which JavaScript code implements shiny's numericInput widget?

A call to numericInput(), like this:
numericInput("obs", "Observations:", 10, min = 1, max = 100)
constructs HTML code like this:
<div class="form-group shiny-input-container">
<label for="obs">Observations:</label>
<input id="obs" type="number" class="form-control" value="10" min="1" max="100"/>
</div>
Then, presumably, in the browser, JavaScript code provided by one of the scripts included in the HTML doc's header finds that <input> element and renders it with the interactive widget displayed below:
I'm having a hard time, though, figuring out where the code that finds that <input> element and then triggers production of the corresponding widget is stored. Is it in Shiny's own JavaScript, or in that borrowed from by Bootstrap or jQuery UI or one of the other plugins that ship with shiny?
My question(s):
Where is the JavaScript code that provides the widget pictured above and associates it with the HTML <input> element? And how, from the code that's involved, might I have learned that on my own?
More only possibly useful details
This section of the script "shiny.js" finds the <input> element of interest, and provides methods that can get and set the widget's value. It doesn't (as far as I can see) provide the widget itself.
var numberInputBinding = {};
$.extend(numberInputBinding, textInputBinding, {
find: function(scope) {
return $(scope).find('input[type="number"]');
},
getValue: function(el) {
var numberVal = $(el).val();
if (/^\s*$/.test(numberVal)) // Return null if all whitespace
return null;
else if (!isNaN(numberVal)) // If valid Javascript number string, coerce to number
return +numberVal;
else
return numberVal; // If other string like "1e6", send it unchanged
},
setValue: function(el, value) {
el.value = value;
[... snip ...]
}
});
inputBindings.register(numberInputBinding, 'shiny.numberInput');
And here is a copy of the <head> section of the the shiny-generated HTML file that results in the numericInput widget. The scripts it references can mostly be found here
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="application/shiny-singletons"></script>
<script type="application/html-dependencies">json2[2014.02.04];jquery[1.11.0];shiny[0.12.2];bootstrap[3.3.1]</script>
<script src="shared/json2-min.js"></script>
<script src="shared/jquery.min.js"></script>
<link href="shared/shiny.css" rel="stylesheet" />
<script src="shared/shiny.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="shared/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
<script src="shared/bootstrap/js/bootstrap.min.js"></script>
<script src="shared/bootstrap/shim/html5shiv.min.js"></script>
<script src="shared/bootstrap/shim/respond.min.js"></script>
<title>Hello Shiny!</title>
</head>
Here's the incorrect assumption that made this so hard for me to figure out:
Then, presumably, in the browser, JavaScript code provided
by one of the scripts included in the HTML doc's header finds that
element and renders it with the interactive widget displayed
below:
In fact, as #epascarello points out, modern browsers themselves support <input type="number">.
(For further documentation of this fact, along with a long list of the features whose support was enabled by the incorporation of JavaScript in these modern web browsers, see Chapter 4 of "HTML for Web Designers".)

Js, document.getElementById("ID").innerHTML, error

Hello I'm new to javascript, and I'm try to write out some code for a test site and I'm having some problems, dow below is my code and I keep getting this error and i can't figure out why.
TypeError: null is not an object (evaluating 'document.getElementById("h3").innerHTML = "<h3>You Are up to date!</h3>"')
This is my second method i tried using. what I'm trying to do it have a have a version list this first one i had was that it would pull a .js file and build a table, but that didn't work so i thought i would try this, but guess what happened? not working
my code that I'm using now is below. if you can help that would be amazing.
thanks, Dakmessier
var current = "1.0";
function get_latest(){
document.getElementById("bob").innerHTML = current;
}
if (local != current){
document.getElementById("Get").innerHTML = "<button>Get the Latest Update!</button>";
} else if (local == current){
document.getElementById("h3").innerHTML = "<h3>You Are up to date!</h3>";
} else {
document.getElementById("h3").innerHTML = "<h3>Sorry, unable to check for update.</h3>";
}
document.getElementById(id) finds an element with a given id value in your HTML. An id value looks like this:
<div id="myHeader">Some Content</div>
And, then you can find that element with:
document.getElementById("myHeader");
ID values must be unique in each document so there should only ever be one element with a given ID.
If an id isn't what you really want, you can find elements other ways, by tag type, by class name, by attribute, etc... using CSS selectors with document.querySelectorAll().
For example, if you wanted to find all <h3> tags, you could do this:
var items = document.querySelectorAll("h3");
Here are some other reasons that document.getElementById(...) might fail to find what you want it to find:
The Javascript code is running before the DOM elements have been parsed and loaded so thus the element is actually not there yet when you're running the code. This is common with code run from the <head> section of the document.
You have an HTML error in how you are specifying the id value in the HTML.
You have an HTML error that causes the browser not to parse your HTML properly.
You have a script error that cause your script to abort before it gets to the part you want to run.
Indeed document.getElementById returns null if it can't find an element with the Id specified.
Also the statement:
if (local != current){
// ..
} else if (local == current){
// ..
} else {
// ..
}
is a bit odd. If local != current is false then local == current must be true. The else if (...) is redundant and the else part will never be run.
hey man the bast thing you should do is the following example, feel free to copy it on your snippet of code:
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed!";
}
<!DOCTYPE html>
<html>
<body>
<p id="demo" onclick="myFunction()">Click me to change my HTML content (innerHTML).</p>
</body>
</html>
I WILL EXPLAIN YOU THIS ANSWER: this is an html + an inline script that makes the inner html work. As far as concerned with your answer it was unclear where your code stopped, anyway test my snippet of code and let me know
I know it's an old question, but I was having the same issue and was trying hard to find the solution for some time.
The problem was that I was executing the script before the page loaded. Thus it wasn't able to find the object that we're trying to catch.
So either use jquery document.ready function or else move your script to the end of the html.
I hope this helps
fix an error of getting the value of a as null
Uncaught TypeError: a is null
code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<script>
let a = document.getElementById('i');
document.addEventListener('mouseup',function(){
a.innerHTML='clean';
})
</script>
<body>
<h3 id="i">not clean</h3>
</body>
</html>
this shows as error in console as
Uncaught TypeError: a is null
you can fix it by making your script tag before
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h3 id="i">not clean</h3>
<script>
let a = document.getElementById('i');
document.addEventListener('mouseup',function(){
a.innerHTML='clean';
})
</script>
</body>
</html>
this might fix!!

Categories