Having issues using js to randomly reassign a css variable - javascript

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.

Related

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!

How to set scale in WKWebview?

I´m trying to modify the scale of a page load in a WKWebView. It is working as far as I´m looking in the html. But the actual scale in the WKWebview doesn´t change.
Here´s how I inject the script:
let script =
"var viewport = document.querySelector(\"meta[name=viewport]\");" +
"viewport.setAttribute('content', 'width=device-width, initial-scale=0.4, user-scalable=0');" +
let userScript = WKUserScript(source: script,
injectionTime: WKUserScriptInjectionTime.atDocumentEnd,
forMainFrameOnly: true)
userContentController.addUserScript(userScript)
Print the html:
webView.evaluateJavaScript("document.getElementsByTagName('html')[0].innerHTML", completionHandler: { (innerHTML, error) in
print(innerHTML)
})
HTML result in console:
Optional(<!--<![endif]--><head>
<title>Bitcoin (BTC) $2391.84 (1.85%) | CoinMarketCap</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=0.4, user-scalable=0">
<meta name="google-site-verification" content="EDc1reqlQ-zAgeRrrgAxRXNK-Zs9JgpE9a0wdaoSO9A">
<meta property="og:type" content="website">
I´m asking myself if this is the right approach. I also tried: let script = document.body.style.zoom = '0.8'; and let script = document.body.style.webkitTransform = 'scale(0.8)'; which is both working in terms of scale, but using this method, the timeperiod slider in this highchart loses its functionality. Any kind of new ideas would be much appreciated.
Add <meta name="viewport" content="width=device-width, shrink-to-fit=YES"> to your HTML file.
(I added right after but not sure if you can add it anywhere)
In my case I have html files for privacy in my Xcode project. I added that javascript code right below the and it did the trick for me.
It works as if you used scalePageToFit in UIWebView.
Hope it helps.

Change Array.prototype in ecmascript (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

Turn off Zurb Foundation 5 meta tags

Searched all over the internet but could not find anything about it.
How can I turn off this zurb foundation 5 meta tags in <head>:
<meta class="foundation-mq-small">
<meta class="foundation-mq-small-only">
<meta class="foundation-mq-medium">
<meta class="foundation-mq-medium-only">
<meta class="foundation-mq-large">
<meta class="foundation-mq-large-only">
<meta class="foundation-mq-xlarge">
<meta class="foundation-mq-xlarge-only">
<meta class="foundation-mq-xxlarge">
<meta class="foundation-data-attribute-namespace">
1) You shouldn't. They are needed for some Foundation's JS plugins.
2) If you want to just use Reveal Modal, you don't need removing these meta tags. You can simply include only this plugin into your webstie:
<script src="/js/foundation.js"></script>
<script src="/js/foundation.reveal.js"></script>
Or, if you are using foundation.min.js, you can init only this plugin:
$(document).foundation('reveal');
3) If you are absolutely confident you want to remove these tags for some reason, you have three possibilities:
Editation of file foundation.js
Remove this part from the file foundation.js.
header_helpers([
'foundation-mq-small',
'foundation-mq-small-only',
'foundation-mq-medium',
'foundation-mq-medium-only',
'foundation-mq-large',
'foundation-mq-large-only',
'foundation-mq-xlarge',
'foundation-mq-xlarge-only',
'foundation-mq-xxlarge',
'foundation-data-attribute-namespace']);
Removal by plain JavaScript (after include)
Include thit code snippet somwhere into your website. It should be run after Foundation initialization.
var metas = document.getElementsByTagName('meta');
for (index = metas.length - 1; index >= 0; index--) {
var metaClass = metas[index].getAttribute('class') || '';
if (metaClass.indexOf('foundation') > -1) {
metas[index].parentNode.removeChild(metas[index]);
}
}
Removal by jQuery (after include)
This code snippet needs jQuery, however, you should have it included already because Foundation depends on it. And, of course, it should be also run after Foundation initialization.
$('meta[class*=\'foundation\']').remove();

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