How to fix custome varible background image change - javascript

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>

Related

How to display result of javascript as HTML link?

I have the following code that I use to retrieve the hostname of a server and append some text (a filename) to it and display it on an html page.
<script type="text/javascript">
function getBaseUrl() {
var re = new RegExp(/^.*\//);
}
</script>
<script type="text/javascript">
document.write(getBaseUrl() + "filename.ext");
</script>
That generates a server URL such as https://fqdn/folder/filename.ext which is exactly what I need. Everything I have tried to create a link from it breaks things. How do I make that generated text clickable?
It's pretty straight forward to do -
const link = getBaseUrl()+ "filename.ext";
createLinkNode(link, document.body);
// defining a function to create a link node, however this isn't neccessary,
// you could just hard code the logic above.
// I wouldn't recommend setting innerHtml in lieu of making a text node however.
function createLinkNode(url, parent) {
const linkTextNode = document.createTextNode(url);
const linkNode = document.createElement('a');
linkNode.href = url;
linkNode.appendChild(linkTextNode);
parent.appendChild(linkNode);
}
example: https://jsfiddle.net/f4wxvLky/3/
You'd need to wrap it in an <a href=''></a>. This is easiest if you assign the <a> element in question to a variable, as you can then use .href to modify the link, along with .innerHTML to modify the text:
function getBaseUrl() {
return 'http://www.google.com/';
}
const output = document.getElementById('output');
output.innerHTML = 'Link Title';
output.href = getBaseUrl() + "filename.ext";
<a id="output" href=""></a>
If you don't have access to the HTML, this can still be done with raw JavaScript by simply including the <a href=''></a> wrapper in your output, being careful to also output the single quotes:
function getBaseUrl() {
return 'http://www.google.com/';
}
document.write("<a href='" + getBaseUrl() + "filename.ext" + "'>Link Title</a>");
Try this out, I assume getBaseUrl() is working although this doesn't look like. Just a reminder that <a> tag needs to be under the <script> block
<script>
function getBaseUrl() {
var re = new RegExp(/^.*\//);
}
</script>
Click

How to use a variable as a filepath in JS?

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>

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.

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);
});

Get url query string and use as src on iframe

I'm completely new at javascript and I'm wondering about something really elementary here. I've got an iFrame that I want a dynamic src on. This src(source) should just be a variable. And then a script sets that variable before the frame is loaded.
It's actually a webpart in Sharepoint 2010, so I set up the webpart and edit it's HTML source to something like this:
<script language="JavaScript">
var qs = getQueryStrings();
var myParam = qs["myParam"];
function getQueryStrings() {
var assoc = {};
var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
var queryString = location.search.substring(1);
var keyValues = queryString.split('&');
for(var i in keyValues) {
var key = keyValues[i].split('=');
if (key.length > 1) {
assoc[decode(key[0])] = decode(key[1]);
}
}
return assoc;
} </script>
<iframe height="500" src="(myParam);" width="800"></iframe>
I'm not even sure the syntax is correct. Basically, I want to insert the variable into the src of the iframe.
you have to give some class or ID to your Iframe.
And then you can call a function which will give src to i frame dyanmically.
from client side use this:
$('#ID_of_Iframe').attr('src','NEW SRC hERE');
Example: $('#ID_of_Iframe').attr('src','www.google.com');
Make your links like this:
File1.PDF
or:
<iframe name='myPdfFrameName'></iframe>
File1.PDF
function loadFrame(href) {
window.frames['myPdfFrameName'].location = href;
return false;
}
EDIT: Easiest is probably using target attribute of a link:
<a href='file1.pdf' target='myPdfFrameName'>File1.pdf</a>

Categories

Resources