I'm trying to create a button that links to a random page in my simple website. I'm having issues modifying the "href" and making it go to the page on the click.
Here is the JavaScript I have written:
document.addEventListener("DOMContentLoaded", function(){
let arrayofpages = ["my_cat.html","about_me","art.html","index.html"]
let randompage = arrayofpages[Math.floor(Math.random()*arrayofpages.length)];
document.addEventListener("click",function(){
document.getElementById("lucky_btn").href = "${randompage}";
document.getElementById("lucky_btn").innerHTML = "random page";
});
The string "${randompage}" is literally just a string that says "${randompage}". Instead, use backticks:
`${randompage}` // This creates a string out of the variable randompage
But in your case, since you're not doing anything with the string, the simplest way is to use the variable directly:
document.getElementById("lucky_btn").href = randompage;
In general, template literals are more useful for inserting variables into a longer string, like
let name = 'Sarah';
let quality = 'great';
let message = `Hello ${name}, have a ${quality} day`;
A little bug in your code. you used double quotes "" instead of backticks ``.
This line
document.getElementById("lucky_btn").href = "${randompage}";
should be
document.getElementById("lucky_btn").href = `${randompage}`;
I have found the bug that was causing the issue, of not redirecting to a random page:
instead of
document.getElementById("lucky_btn").href = "${randompage}";
where I should have used backticks, I changed the code to:
document.location.href = `${randompage}`;
and this has solved the problem!
Related
I'm changing the HTML using javascript. Therefore, I have a String that saves the HTML code, since it is produced in a for-loop. In it there is an <a> tag. To the <a> tag I want to add an onClick which calls a function with a parameter which is saved in a javascript variable.
let parameter = "p1";
let to_html_String = "<a href='#' onClick='create_sprite_window("+parameter+")'></a>";
document.getElementById('sidebar_left_sprites').innerHTML = to_html_String;
This does not work because it would prodece the following html:
<a href='#' onClick='create_sprite_window(p1)'></a>
It does not work because there are no quotation marks before and after p1.
My problem is that I would need a third kind of quotation marks in order to solve this.
In the following example I will use # where I would need those quotation marks:
let parameter = "p1";
let to_html_String = "<a href='#' onClick='create_sprite_window(#"+parameter+"#)'></a>";
document.getElementById('sidebar_left_sprites').innerHTML = to_html_String;
I can't use a single quotation mark because it would end the onClick and I can't use double beacuse it would end to_html_String.
Are there third quotation marks or is there an other way to solve this?
If you're using ES6, you can use template strings like
let foo = `Hello "World's"`;
Anyway - why wouldn't you just escape your quotation marks ?
let bar = 'hello \' world';
let buz = "hello \" world";
Don’t build HTML using JavaScript. The DOM API will let you build document nodes cleanly and safely, and even attach event listeners so you don’t have to build JavaScript strings in the HTML you’re building in JavaScript.
let parameter = "p1";
const link = document.createElement('a');
link.href = '#';
link.textContent = 'maybe you want something in this link?';
link.addEventListener('click', function (e) {
e.preventDefault();
create_sprite_window(parameter);
});
document.getElementById('sidebar_left_sprites')
.appendChild(link);
createElement
addEventListener
appendChild
This will work
"<a href='#' onClick='create_sprite_window('"+parameter+"')></a>";
/* Use \' to differentiate with function single quote */
let parameter = "p1";
let to_html_String = "";
document.getElementById('sidebar_left_sprites').innerHTML = to_html_String;
I'm fairly new to javascript so please go easy on me,
I have this code on a webpage:
<script type="text/javascript"> bb1 = "oldcode"; bb2 = "morecodehgere"; bb3 = 160000;</script>
I want to replace 1% of all page loads oldcode to newcode
There are multiple instances of this code on the same page and I want to replace them all.
window.onload = replaceScript;
function replaceScript() {
var randomNumber = Math.floor(Math.random()*101);
var toReplace = 'oldcode';
var replaceWith ='newcode';
if randomNumber == 1 {
document.body.innerHTML = document.body.innerHTML.replace(/toReplace/g, replaceWith);
}
}
This is the current code I've got but it doesn't work.
Is javascript the bast way to achieve what I'm looking to do? If so whats the best way to do this?
The regular expression literal:
/toReplace/g
will create a regular expression object that matches the string "toReplace". If you want to create a regular expression to match the (string) value of the variable toReplace, you must use the RegExp constructor:
var re = new RegExp(toReplace, 'g');
It is not a good idea to replace the innerHTML of the body with a copy of itself. The innerHTML property doesn't necessarily reflect all the nuances of the DOM and will not include things like dynamically added listeners. It also varies from browser to browser.
Using a regular expression to replace parts of innerHTML is almost certain to produce unpredictable results, it may work well on trivial pages but will not be reliable on complex pages.
I need to get a id from a html element and replace a part of the word. For example:
HTML
<input type="checkbox" id="facebookCheckbox"></div>
JavaScript
var x = document.getElementById("facebookCheckbox");
var name = x.id;
name.replace("Checkbox","");
This obviously does not work because the replacing word has to be standalone for it to be replaced. Is there a different way of doing this?
I'm looking for purely javascript no jQuery
Thank you!
name.replace("Checkbox","");
This obviously does not work because the replacing word has to be standalone for it to be replaced.
No, it does work and there's no need to be "standalone" - any part of the string can be matched. Only you did nothing with the result of the operation:
console.log(name.replace("Checkbox",""));
// or
name = name.replace("Checkbox","");
// or assign back to x.id maybe?
You are creating a copy of string when replacing, so you must assign the result of .replace() back to x.id.
var x = document.getElementById("facebookCheckbox");
x.id = x.id.replace("Checkbox","");
this is not going to work in this way. However you can have a marker kind of character by which you can break the name into array and implement the logic. For example:
var x = document.getElementById("facebook_Checkbox");
//Note I have added underscore in the Id
var name = x.id;
var arr=name.split("_");
//Now you have Checkbox and Facebook as string objects (part of array) and you can use them
name=arr[0]
I hope it will solve the purpose.
I have been trying for hours to fix this code, I can't see what's wrong:
document.getElementById('detail'+num).innerHTML='<a class="dobpicker" href="javascript:NewCal('+s_d+','+ddmmyy+')">'
The problem is in href="javascript ..."
s_d is a javascript variable defined as
var num = 2;
var s_d = "sname"+num;
var ddmmyy = "ddmmyy";
Basically I need to call a javascript function with different parameter each time.
Use a backslash like \'.
document.getElementById('detail'+num).innerHTML=
'<a class="dobpicker" href="javascript:NewCal(\''+s_d+'\',\''+ddmmyy+'\')">'
Since this is the value of a href attribute, HTML encode them:
document.getElementById('detail'+num).innerHTML='<a class="dobpicker" href="javascript:NewCal("'+s_d+'","'+ddmmyy+'")">'
Or better yet don't use the javascript: protocol:
[0,1,2,3,4,5].forEach(function(num) {
var s_r = "sname"+num;
var ddmmyy = "ddmmyy";
var aEl = document.createElement("a");
aEl.className = "dobpicker";
aEl.onclick = function() {
NewCal(s_d, ddmmyy);
}
document.getElementById('detail'+num).appendChild(aEl);
});
Your .innerHTML setting is using s_d, but your variable declaration has s_r.
EDIT: That was the first thing that jumped out at me. Having looked a bit closer and realised the values are strings, I think fixing the variable name together with adding some escaped quotation marks as in Daniel A. White's answer will do the trick.
Just wandering will it be possible to partially string replace in jquery?
I have try to using the following code, but this is not seem working for me:
var test = "testing_supplyAddress_001";
test.replace('supplyAddress', 'billingAddress');
I tried to replace only supplyAddress to billingAddress so the output will be testing_billingAddress _001
JavaScript strings are static and thus .replace() does not actually modify the string. You'll need to assign the value returned by the .replace() function back to the variable:
var test = "testing_supplyAddress_001";
test = test.replace('supplyAddress', 'billingAddress');
Here's a demo showing this in action ->
It works fine. It doesn't replace it in place though - the replace() method returns a new string.
var test = "testing_supplyAddress_001";
var newTest = test.replace('supplyAddress', 'billingAddress');
alert(newTest);
This is just plain old javascript - but will work with jQuery too.
var test = "testing_supplyAddress_001".replace('supplyAddress', 'billingAddress');