How to use a variable as a filepath in JS? - javascript

While trying to build some dynamic content for a webpage, I encountered a strange problem. I did some research but I could not find anything that would help me...
Here is my code where I try to change the background image of a div.
The file path for the background image is stored in an object which is received as JSON and parsed to a javascript object. When I fill the innerHTML of the div with the content of the filepath variable, the correct URL is displayed.
And when I write this exact URL into the backgroundImage URL, the correct picture is displayed.
However when I try to replace the file path with the variable, nothing happens.
var myObj = JSON.parse(this.responseText);
var URL = JSON.stringify(myObj.imageURL);
newbox.style.backgroundImage = "url('myObj.imageURL')";
newbox.innerHTML += myObj.Content;
newbox.innerHTML += myObj.imageURL;
insert.append(newbox);
In my code you can see that I also tried to stringify the value of myObj.imageURL and use this as the file path. But this did not work either.
EDIT: the filepath stored in myObj.imagURL looks like this: images/crew.jpg
EDIT 2: The problem has been solved by Manuel Otto:
newbox.style.backgroundImage = "url("+myObj.imageURL+")";
Thanks for all the advise!

Very close, you were ;)
newbox.style.backgroundImage = "url("+myObj.imageURL+")";

I think your string is wrong.
Use this:
newbox.style.backgroundImage = "url('" + myObj.imageURL + "')";

This is a fully working code.
var myObj = {
imageURL: "https://images.unsplash.com/photo-1494249465471-5655b7878482?ixlib=rb-0.3.5&s=997116405ede44d63ddc54f16e2db8ce&auto=format&fit=crop&w=1350&q=80",
Content: "my div content"
}
var URL = JSON.stringify(myObj.imageURL);
var insert = document.getElementById("insert");
var newbox = document.createElement("DIV");
newbox.style.backgroundImage = `url('${myObj.imageURL}')`;
newbox.style.height = "400px";
newbox.innerHTML += myObj.Content;
newbox.innerHTML += myObj.imageURL;
insert.append(newbox);
<div id="insert"></div>

Related

How to fix custome varible background image change

So I am developing a website where users can change their background image to anything they want(only a URL and on the web) I have given them some choices of my own, that work, but for some reason, the variable is not working.
I have tried
'url(db)';
'url(+db+)';
'url("db")';
<button class="bp" onclick="myown()">My Own background</button>
function myown() {
var db = window.prompt("Image URL");
document.body.style.backgroundImage = 'url(db)';
}
JS basics and concatenating strings and variables. Variable has to be outside quotes, else it's just a string, not variable.
document.body.style.backgroundImage = 'url(' + db + ')';
You need to concatenate variable like this
function myown() {
var db = window.prompt("Image URL");
document.body.style.backgroundImage = "url("+db+")";
}
<button class="bp" onclick="myown()">My Own background</button>
add this sample url to prompt for testing
https://cdn.pixabay.com/photo/2015/03/30/20/33/heart-700141_960_720.jpg
You can use template literal also
function myown() {
var db = window.prompt("Image URL");
let dummyUrl = 'https://cdn.pixabay.com/photo/2015/03/30/20/33/heart-700141_960_720.jpg'
let url = `url(${dummyUrl})`
document.body.style.backgroundImage = url
}
<button class="bp" onclick="myown()">My Own background</button>

Convert string to html tags in Javascript

I want to convert the following string to HTML tags and place it inside my div.
<strong>asdfadfsafsd</strong>
I am using the following code to place it inside my div:
var message = "<strong>testmessage</strong&gt";
document.getElementById('message').innerHTML = bericht;
The problem is that I see the following in my div now:
<strong>testmessage</strong>
But I want to see:
testmessage
What is the problem?
var string = "<strong>asdfadfsafsd</strong>",
results = document.getElementById("results")
results.innerHTML = string;
results.innerHTML = results.textContent;
<div id="results"></div>
At first load the it as html. Then fetch it as text and then again load it as HTML :)
Refer HTML Entities
Try createElement
var tag = document.createElement("strong");
var t = document.createTextNode("testmessage");
tag.appendChild(t);
document.body.appendChild(tag);

using Javascript to link pages from subdomain to another subdomain with same structure subfolder

I am trying to creat a button that will link a subdomain but keep the same path for the page.
clicked it goes from
sub1.maindomain.com/folder01/folder02/folder03/
to
sub2.maindomain.com/folder01/folder02/folder03/
I would like to script it, I want it be added to the site template.
Kinda rusted with my JS.
Thank you if you can give me pointers.
var loc=window.location.href;
var path=loc.substring(19);//flesh this out to be smarter for your use case
var newdomain = "sub2.maindomain.com";
var link=jQuery("#linkid").attr('href',newdomain+path);
You can use the location object.
var path = location.pathname; //pathname will return the complete path of the uri without the host/domain.
var queryString = location.search.length > 0 ? location.search : ""; //this will retrieve the querystring if available.
var newLink = "sub2.maindomain.com" + path + queryString;
document.getElementById("link").href = newLink; //replace [link] with an id from your anchor element/button element.

How to set dynamic image path

I want to use dynamic variable for my image.
I have something like
var img = 'test'
var path = "<img src="'../images/' + img + '_default_path.png'"></img>";
but it gave me errors. I know it might be just the quote issue but I am not sure where went wrong. Can someone please help me on this?
Thanks a lot!
Try this:
var path = '<img src="../images/' + img + '_default_path.png" />';

Adding javascript variable to hyperlink within script

I have been trying to create a hyperlink using a variable defined earlier in the same function to append:
var NAMEVARIABLE = responseArray[i].Name;
var TITLE_Game = document.createElement("p");
TITLE_Game.className = "TITLE_Game";
TITLE_Game.innerHTML = "<a href='Game_NAMEVARIABLE.html'>Games</a>";
I have tried the following using the solution found here: Passing Javascript variable to <a href >
Games
But that didn't work. I then tried adding an ID:
<a id="link" href="Game_.html?propid=">Games</a>
And adding this to the script: document.links["link"].href += NAMEVARIABLE;
This didn't work either. These links are occuring within Isotope, which I've run into newbie-problems making sure my JSON data is loading before the script executes. That's all working now, but I'm not sure if the reason the above methods aren't working is because of a similar issue, or if they simply are not the proper way to go about this.
Any help is much appreciated. Thank you
first of all, try debug your variable :
var NAMEVARIABLE = responseArray[i].Name;
alert(NAMEVARIABLE);
is it returning the desired return value or not.
and then the second thing, in your first style of script, try this instead :
TITLE_Game.innerHTML = "<a href='Game_"+NAMEVARIABLE+".html'>Games</a>";
I assumed you have (static) html collection with game_[number_id].html format
and if it's so, you can try further with your second style of script, and change it to this :
Games
you need to learn further about javascript strings concatenation
Use string concatenation to build up your inner html string.
Example:
var nameVariable = 'Foo';
var innerHtmlText = nameVariable + 'bar';
$('#someElement').html(innerHtmlText);
The contents of someElement will then contain the text: 'Foobar';
You just need string concatenation. modify link's href onclick would be considered as spam in most modern browser.
<div id="result">
the result:
</div>
<script type="text/javascript">
var name = "foo_bar";
var url = "page.html?key=" + name; //or.. "page_" + name + ".html";
var link = 'link here';
$("#result").addClass("g_title");
$("#result").append(link);
</script>
This can be achieved by either (i.e. pure JS or jQuery) ways without much hassle. Suppose you have this <a> element with some href
<a id="Link" href="/collection/categories/">Games</a>
Pure JavaScript way:
window.onload = function() {
var link= document.getElementById('Link'),
url = link.href + responseArray[i].Name + '.html';
link.setAttribute('href', url);
}
Using Jquery:
$(function(){
var link= $('#Link'),
url = link.attr('href') + responseArray[i].Name + '.html';
link.attr('href', url);
});

Categories

Resources