Refresh page adding a new random parameter - javascript

I want to load an url with a random parameter. For example (rnd is a random value):
Load www.website.com?rnd=2398
Push F5
Automatically load www.website.com?rnd=4583
Goto step 3 is you push F5, but with a new rnd value
I tried use onbeforeunload, but I don't want it asks me if I prefer to stay here or to leave the page. I use this function too:
jQuery().ready(function () {
var actualUrl = window.location.href;
var aleat = Math.round(Math.random() * 100000);
if (actualUrl.indexOf('rnd') != -1) {
$("a[href]").attr('href', function (index, href) {
if (href.indexOf("javascript") == -1 && href.indexOf("mailto") == -1) {
return href + (href.indexOf('?') != -1 ? "&rnd=" + aleat : "?rnd=" + aleat);
}
});
}
});
With this function, if I use rnd param then I add a new rnd param in all my href. So when I click in a href, a load the url with a new random param. My problem is...How can I actualize the url using F5/refresh?

You can use this plugin:
https://github.com/carhartl/jquery-cookie
And make something like this:
$(document).ready(function(){
var url = window.location.href;
var rnd = url.split('rnd=')[1];
var cookie = $.cookie("rnd");
var newRnd = Math.round(Math.random() * 100000);
$.cookie("rnd", newRnd);
if(rnd == cookie || !cookie) {
window.location.href = 'http://www.website.com/?rnd=' + newRnd;
}
});
This is just a quick draft, i haven't test it but should be close, hope this helps you.

Related

Random button generator needs fixing to avoid loading the same page

I have a random button generator, named 'next event'. The button is okay however needs an improvement. Sometimes this button loads the same page the user is on multiple times, I'm not sure how to edit this, this is my code.
I could remove the current pages URL, however, this is in a separate JS document and I would like that to be loaded again on further button clicks.
the code used:
var sites = [
'/landingpage/events/uk/boardmasters.html',
'/landingpage/events/uk/reading.html',
'/landingpage/events/uk/rizefest.html',
'/landingpage/events/uk/bestival.html',
'/landingpage/events/uk/creamfields.html',
'/landingpage/events/uk/feastival.html',
'/landingpage/events/uk/fusion.html',
];
function randomSite() {
var i = parseInt(Math.random() * sites.length);
location.href = sites[i];
}
Like this:
function randomSite() {
var i = parseInt(Math.random() * sites.length);
if(location.href !== sites[i])
location.href = sites[i];
else randomSite();
}
UPDATE
Based on the comment if you deleted URL within array I would change the function accordingly. And you don't need pop()
function randomSite() {
var i = parseInt(Math.random() * sites.length);
if(location.pathname !== sites[i])
location.pathname = sites[i];
else randomSite();
}
You could remove the current page from the pages-array before choosing a random item from it:
function randomSite() {
var index = sites.indexOf(window.location.href);
if (index > -1) {
sites.splice(index, 1);
}
var i = parseInt(Math.random() * sites.length);
location.href = sites[i];
}

How to hide and show div if url is set to specific value using jquery/javascript?

I'm sending a specific value through url and after that my page get refreshes.
The URL value is dynamic.Whenever URL sets I want to show div which is already hidden.
<button id="show_id" onclick="location.href='opdcasepaperreport.php?patient_nm='+document.getElementById('patient_id').value;" > View Report </button>
When user clicks on View Report , report div will be displayed.
I tried following 2 coding methods:
$( document ).ready(function()
{
$("#show_id").click(function()
{
$('#main').toggle();
});
});
and
$(document).ready(function ()
{
if(window.location.href.indexOf("?patient_nm"))
{
//alert("your url contains ");
//show code;
}
});
in 1st case because of page refresh div get visible and un visible again.
Is there any solution for this like in php if(isset(---)){//do this;}
Changing location.href value will refresh the page anyway.
In order to hide/show div depending on url value you need to:
get the value by searching in url params.
show / hide div.
Get URL params.
You can use this script in order to get url params:
var getQuery = function () {
var url_params = {};
var query = window.location.search.substring(1);
if (query.length === 0) return false;
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (typeof url_params[pair[0]] === "undefined") {
url_params[pair[0]] = pair[1];
} else if (typeof url_params[pair[0]] === "string") {
var arr = [ url_params[pair[0]], pair[1] ];
url_params[pair[0]] = arr;
} else {
url_params[pair[0]].push(pair[1]);
}
}
return url_params;
};
It will return an object (key, value).
Show / Hide div
If you using jQuery, you can simply is .toggle()
$("#your_div_name").toggle();
Or by using .show() / .hide()
So:
var query = getQuery();
if (query && query.some_param !== undefined) {
$("#your_div_name").show()
} else {
$("#your_div_name").hide()
}
But it's better not to use url params in order to change view.
Have fun.
How about this:
$("#show_id").click(function(e)
{
e.preventDefault();//this will prevent page refresh
$('#main').toggle();
});
Try following code:
$( document ).ready(function()
{
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var hasParam = getParameterByName('patient_nm');
if(hasParam !== 'undefined') {
$('#main').toggle();
}
});
As per your code, on button click the element will get toggled but after that the page gets refreshed immediately. On page refresh the element will be hidden again, so you are not able to view the effect.
As per my code above, when the page refreshes/loads, it will search for the parameter "patient_nm" that you are adding in the URL. If this parameter is not empty it will toggle the element. Since this process happens after page load, you will be able to see the results.
Hope this helps.

Javascript Set Var once

I want to make a Google chrome extension that when i click on it.
then the variable i will go up once and when i click again i want it to go up once more.
when Variable i equals 3 then i want to to set to 0 again.
I want to make a sort of switch.
BACKGROUND.JS
var i = 0;
chrome.browserAction.onClicked.addListener(function(activeTab) {
i = i + 1
if (i == 1) {
var newURL = "http://www.website1.com";
chrome.tabs.create({ url: newURL });
var newURL = "http://www.website2.com";
chrome.tabs.create({ url: newURL });
var newURL = "http://www.website3.com";
} elseif (i == 2) {
chrome.tabs.close()
} else {
var i = 0
}
});
when i click on my Extension notification then it doesnt do anything at all.
and i think the chrome.tabs.close also doensnt work.
var i = 0
Should be outside the function

How can I traverse through cookie and then upon clicking a button change the url depending on values from cookie

I have a cookie dataid giving data as below
"D_2781467,D_2792290,D_2803725,D_2677313,D_2799569,D_2805134,D_2758142,D_2802506,D_2802509,D_2802508,D_2803726,D_2652515"
And in the body we have valies as below
<body class="mycars" data-listing-id="2792290">
And the URL will be like
http://www.abcd.com/c_f_s/D_2792290/xyz.html
What I want is that in this page upon clicking a button , the user is taken to next url as in
http://www.abcd.com/c_f_s/D_2803725
So basically somehow we need to traverse through the cookie and get the index and on pressing the button change the url with the number received from the cookie
You can do it like,
HTML
Next
SCRIPT
$(function(){
var dataArr = ['D_2781467', 'D_2792290', 'D_2803725', 'D_2677313', 'D_2799569',
'D_2805134', 'D_2758142', 'D_2802506', 'D_2802509','D_2802508',
'D_2803726', 'D_2652515'];
var index = 0;
$.cookie('index', 0);
$('#next').on('click', function (e) {
e.preventDefault();
if (index < dataArr.length-1) { // check index length
index++ ;// increment index
} else {
index = 0; // reset index
}
var currentIndex = $.cookie('index'); // get current cookie index from cookie
$.cookie('index', index);
alert('http://www.abcd.com/c_f_s/' + dataArr[currentIndex]);
});
});
You can use cookie plugin
Live Demo
Here is how I would do it (not tested, but this is the basic idea).
using the getCookie function from:
http://www.w3schools.com/js/js_cookies.asp
$('#button').click(function() {
var cook = getCookie('dataid').split(',')
var myId = $('body').eq(0).attr('data-listing-id')
var index = cook.indexOf('D_'+myId)
if (index == -1 || index == cook.length - 1)
return;
document.location = 'http://www.abcd.com/c_f_s/D_'+cook[index+1]
}

FancyBox/ Popup Deeplinking

How do you implement deep linking on a page so when the user comes that that page from an external link, that fancybox modal is initiated. I'm new to JS/Jquery
I was looking for the same thing this morning and found your question as well as a forum post that has an answer.
(function()
{
var qs = location.search.slice( 1 ),
params = qs.match( /&?ab=(\d+)\|(\d+)/ );
if( params )
page( Number( params[ 1 ] ), Number( params[ 2 ] ) );
})();
"Then if you link to that page passing your two numeric parameters in this form:
concert.html?ab=1|5
It should have the stunning effect of calling page(1, 5); when the page loads. "
http://www.webdeveloper.com/forum/showthread.php?t=247899
Hope it helps - it helped me. :)
I just solved it for myself with fancybox2 and url hashes.
You can use Fancybox callbacks to set and unset hashes.
I used data attributes in the img tag to store img identifiers.
Then you can check for a hash in the url at pageload, get the index and open the fancybox with the given index.
var option = {
afterLoad: function(links) {
var title = links.element.attr('data-my-img');
location.hash = title;
},
afterClose: function() {
location.hash = '';
}
},
hash = location.hash.substr(1),
gallery = $('.fancybox');
if(hash.length > 0){
//id
var i = null;
gallery.each(function(index) {
var o = $(this).attr('data-my-img');
if($(this).attr('data-my-img') == hash){
i = index;
return;
}
});
if(i != null){
option.index = i;
$.fancybox.open(gallery, option);
}
}
gallery.fancybox(option);

Categories

Resources