I know it's a silly mistake but I can't figure it out. I have been searching for it for the past 3 days. Basically, I have a function that changes the theme of a page by modifying CSS using Javascript. All properties are modified correctly, except the backgroundImage, don't know why. Here's the function:
function enforceTheme() {
document.body.style.backgroundColor = theme["bgColor"];
const background = "https://via.placeholder.com/300/09f/fff.png";
document.body.style.backgroundImage = 'url('+background+');';
document.getElementById("upBtn").style.color = theme["upBtnColor"];
document.getElementById("downBtn").style.color = theme["downBtnColor"];
}
The strange thing is that the code gives no error and works fine, except for the backgroundImage not showing. And it works if I set it using CSS stylesheet. But I need to change it dynamically, so using Javascript.
You have to use Template Literals
Try this
function enforceTheme() {
document.body.style.backgroundColor = theme["bgColor"];
const background = "https://via.placeholder.com/300/09f/fff.png";
document.body.style.backgroundImage = `url('${background}')`;
document.getElementById("upBtn").style.color = theme["upBtnColor"];
document.getElementById("downBtn").style.color = theme["downBtnColor"];
}
Related
I have an odd issue. I am attempting to set a CSS variable and change this dynamically on page load.
It works fine in my rudimentary jsfiddle here: https://jsfiddle.net/lharby/jw6t0krm/
The basic code is:
const colours = ['#ee4800','#60c600','#00ffff','#ff7f00','#ff6ccc','#848382','#d2dd26'];
const rndColour = Math.floor(Math.random() * colours.length);
document.documentElement.style.setProperty("--selection-background", colours[rndColour]);
My app is more complex in using transpiling, so my setColourFunction looks like this:
const colours = ['#ee4800','#60c600'...]; // same as previous array
const rndColour = Math.floor(Math.random() * colours.length);
const setRandomColour = () => {
document.documentElement.style.setProperty(
'--selection-background',
colours[rndColour]
);
};
export { setRandomColour };
Then, in my main app, I am importing like so:
import { setRandomColour } from './js/randomColours';
$(document).ready(() => {
if (DOM.classList.contains('high-contrast')) {
setRandomColour();
}
}
In the browser, the background colour is set as a pink tone by default (which is one of the items inside the colour array). If I hover over the scrollbar or click the navigation, the scrollbar changes colour to the correct value in the variable. I assumed this might be some Chrome bug, but the jsfiddle seems to work fine.
You can see an example of the live app here: https://studiomalarkey.co.uk/
At one time, I did have a reference to my minified script using the defer method, and thought this might be the issue, but I have removed that property now.
Does anyone know why this might be happening?
I need to implement 4 scripts, the last one has one function that I always get undefined, I have implemented it on a website without React, but at react I'm having a lot of problems.
componentDidMount () {
this.mountLeadpointScript();
}
mountLeadpointScript() {
const disclosureScript = document.createElement('script');
disclosureScript.id = 'disclosureSr';
disclosureScript.type = 'text/javascript';
disclosureScript.async = true;
document.body.appendChild(disclosureScript);
const srScript = document.createElement('script');
srScript.id = 'srScript';
srScript.type = 'text/javascript';
srScript.async = true;
document.body.appendChild(srScript);
const dataVerifyScript = document.createElement('script');
dataVerifyScript.src = '"//www.dataverify123.com/js/sr-min.js';
dataVerifyScript.async = true;
document.body.appendChild(dataVerifyScript);
dataVerifyScript.onload = () => {
window.leadpoint_dataLayer = [{ 'a': '00000', 'i': '11111' }];
window.LeadpointSecureRights.startSrTokenProcess('www.dataverify123.com');
}
}
Not displaying the real values of a & i.
Always getting undefined, i have tried withouth window, using this, putting it on the html of the app, nothing works.
Thanks in advance.
I'll attach a picture of how it should be implemented enter image description here
The solution from #Salah worked, I was trying to display a disclaimer from that script and it wasn't working due that the div wasn't being rendered when the script was executing, at the end, I ended up using a set timeout so the component will be rendered and then the script is going to execute correctly.
Otherwise, if there is a solution where I can avoid using it on the HTML would be great.
well, to solve that, you may have to paste those scripts in the index.html file, if you are using create-react-app, you will find it in: public/index.html.
Hope that helps
This code is supposed to toggle between the "like" and "unlike" images, except it doesn't. Can anybody tell me what i wrote wrong. And yes i am new to javascript.
<script>
function imgclick(){
var like = "like.png",
unlike = "unlike.png";
var liked = document.getElemendById("liked");
liked.src = (liked.src === unlike)? like : unlike;
}
</script>
<img src="unlike.png" id="liked" width="200" height="200" onclick="imgclick();">
You made a typo in the following line:
var liked = document.getElemendById("liked");
You put getElemendById when it should be getElementById:
var liked = document.getElementById("liked");
If you are new to JS I just want to recommend to you to use relative paths every time you can, because it is going to save you a headache in the future.
It goes like this: var like = "./like.png"
I am currently trying to open an image in a new window by clicking on it. But i cant seem to figure out where my code is wrong. Any solution?
function largePic(){
var imageNumber = document.getElementById("img2");
imageNumber = this.getAttribute('src').split(".", 1);
window.open(imageNumber[0] + "zlatan-stor.jpg");
}
You should try changing "this.getAttribute('src').split(".",1);" to
imageNumber.getAttribute('src').split(".",1);
Are you sure that #img2 is the one being clicked? If it isn't just do it like this:
function largePic(){
var imageNumber = document.getElementById("img2");
var link = imageNumber.getAttribute('src').split(".", 1);
window.open(link[0] + "zlatan-stor.jpg");
}
this will work only if the function is called inline (which you shouldn't do it, you should have your js code in a separated file)
This question is very similar to yours.
I think the main problem with your code is that window.open expects a URL and one isn't being provided.
Following the answer found at this link should allow you to separate the code into an external file, which as #Skatox mentioned, is a good practice.
No idea what I'm doing or why it isn't working. Clearly not using the right method and probably won't use the right language to explain the problem..
Photogallery... Trying to have a single html page... it has links to images... buttons on the page 'aim to' modify the path to the images by finding the name currently in the path and replacing it with the name of the gallery corresponding to the button the user clicked on...
example:
GALLERY2go : function(e) {
if(GalleryID!="landscapes")
{
var find = ''+ findGalleryID()+'';
var repl = "landscapes";
var page = document.body.innerHTML;
while (page.indexOf(find) >= 0) {
var i = page.indexOf(find);
var j = find.length;
page = page.substr(0,i) + repl + page.substr(i+j);
document.body.innerHTML = page;
var GalleryID = "landscapes";
}
}
},
There's a function higher up the page to get var find to take the value of var GalleryID:
var GalleryID = "portfolio";
function findGalleryID() {
return GalleryID
}
Clearly the first varGalleryID is global (t'was there to set a default value should I have been able to find a way of referring to it onLoad) and the one inside the function is cleared at the end of the function (I've read that much). But I don't know what any of this means.
The code, given its frailties or otherwise ridiculousness, actually does change all of the image links (and absolutely everything else called "portfolio") in the html page - hence "portfolio" becomes "landscapes"... the path to the images changes and they all update... As a JavaScript beginner I was pretty chuffed to see it worked. But you can't click on another gallery button because it's stuck in a loop of some sort. In fact, after you click the button you can't click on anything else and all of the rest of the JavaScript functionality is buggered. Perhaps I've introduced some kind of loop it never exits. If you click on portfolio when you're in portfolio you crash the browser! Anyway I'm well aware that 'my cobbled together solution' is not how it would be done by someone with any experience in writing code. They'd probably use something else with a different name that takes another lifetime to learn. I don't think I can use getElement by and refer to the class/id name and parse the filename [using lots of words I don't at all understand] because of the implications on the other parts of the script. I've tried using a div wrapper and code to launch a child html doc and that come in without disposing of the existing content or talking to the stylesheet. I'm bloody lost and don't even know where to start looking next.
The point is... And here's a plea... If any of you do reply, I fear you will reply without the making the assumption that you're talking to someone who really hasn't got a clue what AJAX and JQuery and PHP are... I have searched forums; I don't understand them. Please bear that in mind.
I'll take a stab at updating your function a bit. I recognize that a critique of the code as it stands probably won't help you solve your problem.
var currentGallery = 'landscape';
function ChangeGallery(name) {
var imgs = document.getElementsByTagName("img") // get all the img tags on the page
for (var i = 0; i < imgs.length; i++) { // loop through them
if (imgs[i].src.indexOf(currentGallery) >= 0) { // if this img tag's src contains the current gallery
imgs[i].src = imgs[i].src.replace(currentGallery, name);
}
}
currentGallery = name;
}
As to why I've done what I've done - you're correct in that the scope of the variables - whether the whole page, or only the given function, knows about it, is mixed in your given code. However, another potential problem is that if you replace everything in the html that says 'landscape' with 'portfolio', it could potentially change non-images. This code only finds images, and then replaces the src only if it contains the given keyword.