Function maybe written wrong, doesn't toggle image - javascript

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"

Related

Android Webview not showing backgroundImage from Javascript

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"];
}

Fall back image with SvelteKit

I got started with Svelte(Kit) and I really like it so far. However, I ran into an issue that I couldn't resolve.
I'm trying to dynamically display images and like to have a fall back image in case the normal one does not exist.
With vanilla HTML/JS, I would use this Source:
<img src="imagefound.gif" onerror="this.onerror=null;this.src='imagenotfound.gif';" />
I tried to make it happen in my Svelte project, but it either does not work (e.g. A) or it works sometimes (for a brief moment or until I refresh (e.g. B)).
This is my code (A):
<script>
let profileImg = person.profile;
const missingProfile = () => {
console.log('image does not exist');
profileImg = '../default.png';
};
</script>
...
<img
src={profileImg}
on:error={missingProfile}
alt={person.name}
/>
or just the hardcoded version (B)
<img
src="imagefound.gif"
onerror="console.log('image not found');this.onerror=null;this.src='./person.png';"
/>
There is this question, but I believe the answer is what I am doing. Is there a difference whether I use SvelteKit vs. Svelte?
Addition
It looks like that Svelte does not even set the src for the <img />, if the original variable with the url for the image is undefined (in my example person.profile). The accepted answer wouldn't work in that case.
I edited this line to prevent that case:
let profileImg = person.profile === undefined ? '../default.png' : person.profile;
This code works in SvelteKit
<script>
let fallback = 'http://placekitten.com/200/200'
let image = ""
const handleError = ev => ev.target.src = fallback
</script>
<img src={image} alt="" on:error={handleError}>

Im building a clicker game and localstorage is returning with nothing instead of saved data

So I'm building a clicker game on CodePen and I ran into a problem while coding my save/load functions. It seems as if my save function may not me working, but I'm not sure why.Here are the functions:
function savegame(){
localStorage.clicks = Number(document.getElementById('clicks').innerHTML);
localStorage.cps = document.getElementById('cps').innerHTML;
localStorage.clickPower =
Number(document.getElementById('clickpower').innerHTML);
localStorage.onecpow = Number(document.getElementById('1clickpowe').innerHTML);
localStorage.onecps = Number(document.getElementById('1cps').innerHTML);
localStorage.fivecps = Number(document.getElementById('5cps').innerHTML);
localStorage.fivecpow = Number(document.getElementById('5clickpower').innerHTML);
localStorage.tencps = document.getElementById('10cps').innerHTML;}
function loadgame(){document.getElementById('1clickpower').innerHTML = localStorage.getItem("onecpow");
document.getElementById('clicks').innerHTML = localStorage.getItem("clicks");
document.getElementById('cps').innerHTML = localStorage.getItem('cps');
document.getElementById('clickpower').innerHTML = localStorage.getItem('clickpower');
document.getElementById('5clickpower').innerHTML = localStorage.getItem('fivecpow');
document.getElementById('5cps').innerHTML = localStorage.getItem('fivecps');
document.getElementById('1cps').innerHTML = localStorage.getItem('onecps');
document.getElementById('10cps').innerHTML = localStorage.getItem('tencps');}
I forgot to clarify what I'm expecting the code to do. What this should do is save the players progress and upgrades, instead upon loading the saved data the players data is not loaded and returns many blank spaces where saved data should have been loaded.
Instead of doing localStorage.onecpow = "someValue" try
storage.setItem(onecpow, "someValue");
You can check the Storage docs here for more info
You are using 'localStorage' wrong. Have a look at this:
// writing to localStorage
localStorage.setItem('myId', value);
// reading from localStorage
var whatever = localStorage.getItem('myId');
// remove an item from localStorage
localStorage.removeItem('myId');
EDIT:
The problem is that you're mixing up 2 different approaches. You have to decide which one to use. Either the object-driven or the key-driven.
My example above is the key-driven approach. You should also be able to use the object-driven approach like this:
// writing to localStorage
localStorage.myObject = value;
// reading from localStorage
var whatever = localStorage.myObject;
Choose your style, but don't mix them. ;o)
I found a solution, though it's kind of strange how it works.
I added capital letters to the localStorage attributes and used localStorage.setItem and localStorage.getItem. Don't know why it works but it does.

show image in a new window

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.

onClick replace /segment/ of img src path with one of number of values

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.

Categories