How I would go about making a website that randomly redirects between multiple (in this case 2) websites?
Obviously what is below doesn't work due to what I hope is the meta tag; I would like to know if the javascript code is the correct way to do this
and how it would work.
<head>
<meta http-equiv="refresh" content="1;url=http://example1.com">
<script type="text/javascript">
if Math.random() =< 0.5;
window.location.href = "http://example1.com/"
else;
window.location.href = "http://example2.com"
</script>
<title>Page Redirection</title>
</head>
your javascript syntax inside script tag is not correct either
<script type="text/javascript">
if ( Math.random() <= 0.5 ) //proper parenthesis surrounding the condition and also < will come before =
window.location.href = "http://example1.com/";
else //semicolon removed from here
window.location.href = "http://example2.com";
</script>
You did it right (almost), Wrap the condition in () and remove ;, it will break the if.
if (Math.random() =< 0.5)
window.location.href = "http://example1.com/";
else
window.location.href = "http://example2.com";
Keep in mind one little fact.
if(false)
alert(1);
Won't alert anyting as the if condition is always false. But if you see
if(false); // If will break here.
alert(1);
Will always alert as if breaks and then the execution proceeds without if.
You could make the function a little bit more generic:
var sites = [
'http://www.dilbert.com',
'http://stackoverflow.com',
'http://Starwars.com'
];
var target = Math.floor(Math.random() sites.length);
window.location = sites[target];
So when your site collection grows you don't need to alter the code. You could even pack it into a function:
function goRandomSite(sites) {
var target = Math.floor(Math.random() sites.length);
window.location = sites[target];
}
Hope that helps
Related
First things first, I'm brand new to Javascript and Regex. I've only been dipping my toes in this past month. I've been trying to put together away to paste a url into a text input then automatically trim it down to just the host name and validate it before I'm able to push the button.
I've gotten it working a few different times but I keep running into the same issue: After a certain period of time, it simply stops working.
I've reformatted and cleaned up the code a few times (though, I'm sure it's still very sloppy because I'm new at this) and I can get it working again. But after an hour or so of working, it stops working. Reloading the page doesn't make a difference. Even restarting my computer doesn't make a difference. It simply stops working.
My only guess is that there must be something about the way I'm going about this which is causing it crash or stall out. Perhaps a formatting issue, perhaps the methodology altogether is flawed. I just don't know enough to be able to diagnose it yet.
Hopefully, some of you nice people would be able to point out my flaws or point me in the right direction of how to fix this. I've searched and I couldn't find anyone who was trying to do the things I'm doing all in one build (preparing to myself to be proved wrong here).
Here's the code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<input id="notesUrlInput" type="text" placeholder="URL Goes here" pattern="^(?!www\.)[a-zA-Z0-9\-]+\.[a-zA-Z0-9]+$" autocomplete="off">
<button id="notesExecuteButton" disabled>Execute</button>
<span id="notesUrlOutput"></span>
<!------------------------------------------------------------------------------->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script>
(function () {
var timeout = null;
var notesUrlOutput = document.getElementById("notesUrlOutput");
var notesExecuteButton = document.getElementById("notesExecuteButton");
document.getElementById('notesUrlInput').addEventListener('keyup',
function (e) {
clearTimeout(timeout);
timeout = setTimeout(
function () {
rawInput = $('#notesUrlInput').val();
cleanInput = rawInput.replace('www.', '');
cleanInput = cleanInput.replace('http://', '');
cleanInput = cleanInput.replace('https://', '');
cleanInput = cleanInput.replace(/\/.*/,'');
$('#notesUrlInput').val(cleanInput);
if (cleanInput.value == "") {
notesUrlOutput.innerHTML = "";
notesExecuteButton.disabled = true; return false;
} else if(!notesUrlInput.checkValidity()) {
notesUrlOutput.innerHTML = "Invalid URL: Please provide a valid URL";
notesExecuteButton.disabled = true; return false;
} else {
notesUrlOutput.innerHTML = "Input OK";
notesExecuteButton.disabled = false; return false;
}
}, 400);
});
})();
</script>
</body>
</html>
Frustratingly, when I pasted this code in here and ran it, it worked. As soon as I opened the file I copied this from in my browser. It stopped working. I just don't understand it.
From your code it looks like you want to extract just the domain name from the input field.
You mix JavaScript DOM calls and jQuery, which is fine. It is usually easier to interact with the DOM using just jQuery. Here is your code rewritten in jQuery:
const cleanRegex = /^https?:\/\/(?:www\.)?(.*)\/.*$/;
const validRegex = /^[\w\-]+(\.[\w]+)+$/;
(function () {
$('#notesExecuteButton').prop('disabled', true);
$('#notesUrlInput').on('input', function(event) {
let val = $(this).val();
let cleaned = val.replace(cleanRegex, '$1');
$(this).val(cleaned);
if(!cleaned) {
$('#notesUrlOutput').text('');
$('#notesExecuteButton').prop('disabled', true);
} else if(!cleaned.match(validRegex)) {
$('#notesUrlOutput').text('Invalid URL: Please provide a valid URL');
$('#notesExecuteButton').prop('disabled', true);
} else {
$('#notesUrlOutput').text('Input OK');
$('#notesExecuteButton').prop('disabled', false);
}
});
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<input id="notesUrlInput" />
<button id="notesExecuteButton" style="disabled: disabled;">Go</button>
<div id="notesUrlOutput"></div>
Explanation:
.on('input') - fires every time something changes in the input field- val.replace(cleanRegex, '$1') - clean up: strip protocol and www prefix, and URL path (any text after domain
cleaned.match(validRegex) - check validity of domain
.prop('disabled', true/false) - add/remove disable property
I'm trying to open build a system which opens a new link every time an anchor tag is clicked. I tried using random function but at times it opens the same link again and again. But whereas as I want the link to open in an order and follow the cycle.. That is if I have three links, the user clicking the anchor text first time will open the first link, then second, then third and later again the first link..
This means the link must change if a different user clicks.
Here is a code that I found which uses random function..
<script type="text/javascript'>
function random_3(){
var myrandom=Math.round(Math.random()*2)
var link1="http://www.codingforums.com"
var link2="http://www.cssdrive.com"
var link3="http://www.dynamicdrive.com"
if (myrandom==0)
window.location=link1
else if (myrandom==1)
window.location=link2
else if (myrandom==2)
window.location=link3
}
</script>
<form>
<input type="button" value="random link!" onClick="random_3()">
</form>
so can someone help me out with this?
I tried using random function but at times it opens the same link again and again
You're probably getting the same link several times in succession due to the random calculation that you're using.
Try the following instead:
var myrandom=Math.floor(Math.random()*3);
You should get a better distribution this way.
Now, regarding your original question, if you want a persistent state to be kept between page reloads, so that each time the link is different, you'll probably need to use cookies or localStorage for storing what was the last used index for that user.
Example:
var links = ['http://www.codingforums.com', 'http://www.cssdrive.com', 'http://www.dynamicdrive.com'];
function nextLink() {
var index = localStorage.getItem('lastPos') || -1;
index = (index + 1) % links.length;
localStorage.setItem('lastPos', index);
return links[index];
}
What you need to do is save the index of the link, and then increase it every time so that you cycle through the links in order.
Here's a working example of what you want:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script>
urls = ['http://domain1.com','http://domain2.com', 'http://domain3.com', 'http://domain4.com'];
var urlIndex = 0;
function openUrl(){
url = urls[urlIndex % urls.length];
window.location = url;
urlIndex ++;
}
</script>
Get a link
</body>
</html>
Here's a demo :)
First of all, you have to list your links in an array. Second, you have to define a variable that hold the last opened link's index in that array, to void a successive opening of the same link (indeed it's a URL). In general you may follow something like the following code:
urls = ['http://domain1.com','http://domain2.com', 'http://domain3.com', 'http://domain4.com'];
var lastUrl = '';
function getRandomIndex(arr){
return Math.floor(Math.random() * ((arr.length+1) - 1));
}
function openUrl(){
url = urls[getRandomIndex(urls)];
do {
if (url == lastUrl){
url = urls[getRandomIndex(urls)];
}
else{
lastUrl = url;
//Using alert instead of window.location for testing
alert(url)
//window.location = url;
}
}
while (lastUrl != url);
}
Then for test:
Click here for test
This is an online Demo
Reference: Generating random whole numbers in JavaScript in a specific range?
Edit
According your comment, the requirement is pretty easier, instead of choosing according to random value, you will define lastUrl as an integer store and every time the openUrl() is called, it will be increased by 1 after checking its value if it is greater than urls array length or not as follows:
Modified openUrl
urls = ['http://domain1.com','http://domain2.com', 'http://domain3.com', 'http://domain4.com'];
//lastUrl Index in urls array
// Global variable
var lastUrl = 0;
function openUrl(){
if (lastUrl > (urls.length - 1)){
//reset it to 0
lastUrl = 0;
}
else{
url = urls[lastUrl];
lastUrl++;
alert(url)
//window.location = url;
}
}
var myrandom = 0;
function random_3(){
myrandom += 1;
var link1="http://www.codingforums.com";
var link2="http://www.cssdrive.com";
var link3="http://www.dynamicdrive.com";
if (myrandom==1)
window.open('http://www.codingforums.com','_blank');
else if (myrandom==2)
window.open('http://www.cssdrive.com','_blank');
else if (myrandom==3)
window.open('http://www.dynamicdrive.com','_blank');
else if (myrandom>3)
window.open('http://www.codingforums.com','_blank');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<form>
<input type="button" value="random link!" onClick="random_3()">
</form>
You can count click like user click on button and basis on this manage.
i have this function in my init.js
function bodyresize() {
var factor = ($window.width() * $window.height()) / (1440 * 900);
$body.css('font-size', Math.min(Math.max(Math.floor(factor * settings.sizeFactor), settings.sizeMin), settings.sizeMax) + 'pt');
$main.height(panels[activePanelId].outerHeight());
$body._reposition2();
};
$body._reposition2 = function() {
if (skel.vars.isTouch && (window.orientation == 0 || window.orientation == 180))
$wrapper.css('padding-top', Math.max((($window.height() - (panels[activePanelId].outerHeight() + $footer.outerHeight())) / 2) - $nav.height(), 30) + 'px');
else
$wrapper.css('padding-top', ((($window.height() - panels[firstPanelId].height()) / 2) - $nav.height()) + 'px');
};
now i need from my game1 scrip that when i press a button the code above runs
in my index.html i have this:
<head>
<script src="js/init.js" type="text/javascript"></script>
</head>
and the button i have this
<button id="button" onclick="bodyresize()">Click Me test</button>
i think something is wrong with the button because he cant find bodyresize but i cant find why
This is going against your original approach a little bit, but I would handle the entire thing in Javascript. It could look something like this:
document.getElementById('button').onclick = function(e) {
// your code
}
Here's a working example.
Edit:
Here's another example of a button working of onclick defined in the element itself. It looks similar to what you originally had.
Both of these approaches are technically correct, but if you define the onclick function inside init.js, you can't really reuse the file in another page, as the onclick function would throw an error when it couldn't find another component of the same name (button). A solution around this is define a new file.
Hope this helps you!
I am having an issue implementing this calculator on my website which i created. I think i have used the wrong javascript to create the simple calculation which is the following math calculation: ((list price - rrp) / list price) * 100
PLEASE NOTE, i am aware of the values not being numbers, please replace them with any numbers. it still doesnt work.
This is to get the percentage value of the discount against the list and the RRP.
Please review the code before HTML:
<script type="text/javascript">
discountFinal(#OriginalPrice, #ListPrice);
</script>
<div id="discountCode">
<span id="spanish"></span>
<span id="spanishtwo">%</span>
</div>
Javascript:
var discountFinal = function (firstly, secondly) {
var totalfirst = secondly - firstly;
var totalsecond = totalfirst / secondly;
var totalthird = totalsecond * 100;
if (document.getElementById("discountCode").innerHTML === null) {
document.getElementById("spanishtwo").innerHTML.replace("%", "")
} else {
document.getElementById("spanish").innerHTML = Math.floor(totalthird / 5) * 5
}
};
I dont think i am calling the function within the html properly. Can someone assist with this please.
http://jsfiddle.net/xwzhY/
I'm not sure the error you're getting, but it seems as if you're calling the discountFinal function before it's defined. When you move the call, it starts to work:
http://jsfiddle.net/bmonty/xwzhY/4/
Edit after comment from OP.
You just need to make sure your discountFinal function is defined at the top of your page, before any place it gets called.
This will work:
<script type="text/javascript">
var discountFinal = function(a, b){};
</script>
<script type="text/javascript">
var result = discountFinal(1, 2);
</script>
But this will throw an error:
<script type="text/javascript">
var result = discountFinal(1, 2);
</script>
<script type="text/javascript">
var discountFinal = function(a, b){};
</script>
To get some clarification, View Source on the HTML page from your browser to see what the resulting page looks like. That should point out where the order of operations is getting messed up.
It works fine if you call your function after it exists: http://jsfiddle.net/xwzhY/2/
Just make sure that the function is declared earlier in the code than you use it. Or declare it using a function statement rather than a function expression assigned to a variable:
function discountFinal(firstly, secondly){
...
Trying put "" around your perl variable, you need to pass the value
I've got a webpage which is meant to generate a random number, then when the number =5 it displays a win message..if not display lose message, but its not displaying any alerts..have i missed something out?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function WinLose()
{
var x=document.getElementById("demo");
x=x.innerHTML=Math.floor((Math.random()*5)+1);
return x;
if (x=4)
{
alert("winner!");
}
else
{
alert("loser");
}
}
</script>
</head>
<body>
<p id="demo">Click the button to display a random number between 1 and5.</p>
<button onclick="WinLose()">Try it</button>
</body>
</html>
EDIT:
Managed to get this bit working so now it displays either win or loose depending on its number, yet does anyone know how i can swap the alerts in the if statements to display a DIV section. ive got a jQuery file included so it can accept the hide/show effect...anything i tried didnt work
you have return x after you generate a random value for x. this means no javascript code after that line will run in that function.
also, your if statement needs to use '==' to do the comparison rather than '=' which is assignment.
Yeah, It can be tough. The main problem again has to be other than return x is the "==". So this
if (x=4)
Should really say:
if (x==4)
What you said before was that you were assinging x to 4 so that has no meaning at all and messes everything up.
Hope this helps you!
You need to return x after you generate the random value; and you must add x == 4
function WinLose()
{
var x=document.getElementById("demo");
x=x.innerHTML=Math.floor((Math.random()*5)+1);
if (x==4) {
alert("winner!");
} else {
alert("loser");
}
return x;
}
DEMO
Your code:
x=x.innerHTML=Math.floor((Math.random()*5)+1);
x is receiving x.innerHTML then x.innerHTML = random number.
Correct way: (remove "x=")
x.innerHTML = Math.floor((Math.random()*5)+1);
Here is a simplified version that externalizes the alerts (I assume you don't plan to use them later)
function WinLose(){
var x=Math.floor((Math.random()*5)+1);
document.getElementById("demo").innerHTML=x;
return (x==5) ? "Winner!" : "Loser";
}
alert(WinLose());