Toggle between functions - only execute either one on pageload - javascript

I want to toggle between two jQuery functions. It has to be done on page load - and each page load should only execute one of the scripts.
This is what I got so far:
HTML:
<button class=".click">Click me</button>
Script:
$(function() {
if (window.location.href.indexOf("addClass") > -1) {
$("body").addClass("test");
}
else {
$("body").addClass("secondtest");
}
$('.click').on('click', function() {
console.log("Clicked");
var url = window.location.href;
if (url.indexOf('?') > -1) {
url += '?param=addClass'
} else {
url += '?param=1'
}
window.location.href = url;
});
});
This Gets me a bit on the way, the first click adds ?param=1 on the first click - nothing happens - second click it adds the ?param=addClass and the body gets the class. If I click again it adds ?param=addClass every time.
I want one of the script to run as default - then I want the first button click to reload and run the other script instead. If I click once more I want it to reverse the url so the first script loads, like a toggle.
I now there is an easy way to just toggle classes, but I specifically need to run one of two scripts on a new page load.
Update:
$(function() {
if (window.location.href.indexOf("addClass") > -1) {
$("body").addClass("test");
}
else {
$("body").addClass("secondtest");
}
$('.click').on('click', function() {
console.log("Clicked");
var url = window.location.pathname;
var url = window.location.href;
if (url.indexOf('?param=1') > -1) {
url = url.replace("param=1", "")+'param=addClass'
} else {
url = url.replace("?param=addClass", "")+'?param=1'
}
window.location.href = url;
});
});
This set the body class on first page load - then first click ads ?param=1 but doesnt change the body class. Second click replaces ?param=1 with ?param=addClass and changes the body class - after that the toggles works. So How do I make it work from the first click?

This will be the default functionality, if no query string is present then add ?param=1:
var url = window.location.href;
if(url.indexOf('?param=1')==-1 )
{
window.location.href = url+"?param=1";
}
This will be the onclick functionality to toggle the urls as it is replacing the existing functionality.
$('.click').on('click', function() {
var url = window.location.href;
if (url.indexOf('?param=1') > -1) {
url = url.replace("param=1", "")+'param=addClass'
} else {
url = url.replace("?param=addClass", "")+'?param=1'
}
window.location.href = url;
});
If you want to toggle the classes as well you can use .toggleClass("test secondtest")

The issue you have is in this if:
var url = window.location.href;
if (url.indexOf('?') > -1) {
url += '?param=addClass'
} else {
url += '?param=1'
}
Scenario 1: /test.html
indexOf('?') will be negative. You will then redirect the user to /test.html?param=1
Scenario 2: /test.html?param=1
indexOf('?') will then be positive. You will then redirect the user to /test.html?param=1?param=addClass
Scenario 3: /test.html?param=addClass
indexOf('?') will then be positive. You will then redirect the user to /test.html?param=addClass?param=addClass
So... what is wrong?
You are using window.location.href. Excellent for setting the path but bad if you want to actually manage the query parameters.
Solution
var url = window.location.pathname;
var hasParams = window.location.href.indexOf('?') > -1;
if (hasParams) {
url += '?param=addClass'
} else {
url += '?param=1'
}
window.location.href = url;
Since you are redirecting on the same host (seen with your code), you only need the pathname. pathname doesn't include parameters (?key=value&...) and can be used to redirect a user on the same domain.

Related

Want to refresh page one time on particular URL hit

I am trying to refresh the page only one time when a particular URL is hit.
The reason for this is to refresh the data on the view. My URL is
http://localhost:8072/web?#min=1&limit=80&view_type=list&model=pos.order&action=405
And solutions I have tried are
window.onload = function() {
//considering there aren't any hashes in the urls already
if(!window.location.hash) {
//setting window location
window.location = window.location + '#loaded';
//using reload() method to reload web page
window.location.reload();
}
}
(function()
{
if( window.localStorage )
{
//check if reloaded once already
if( !localStorage.getItem('firstLoad') )
{
//if not reloaded once, then set firstload to true
localStorage = true;
//reload the webpage using reload() method
window.location.reload();
}
else
localStorage.removeItem('firstLoad');
}
})();
$(document).ready(function(){
//Check if the current URL contains '# or hash'
if(document.URL.indexOf("#")==-1){
// Set the URL to whatever it was plus "#loaded".
url = document.URL+"#loaded";
location = "#loaded";
//Reload the page using reload() method
location.reload(true);
}
});
None of them worked for me. What is wrong or which direction should I choose?
Your first solution works fine, it just needed a return statement to prevent execution the rest of the code, however if your original url contains a hash, you can do the check like this:
window.onload = function() {
document.getElementById("test").textContent = window.location;
console.log(window.location.hash);
//check for our specific hash argument
if (!window.location.hash.match(/[#&]loaded(&|$)/)) {
alert("the page is about to refresh");
//setting window location
window.location = window.location + (window.location.hash ? "&" : "#") + 'loaded';
//using reload() method to reload web page
window.location.reload();
return;
}
alert("page refreshed");
}
<div id="test"></div>

how to refresh the page with original URL when URL has been changed via history.pushState()

I have used history.pushState() and now if the user refreshes the page then it is refreshing current URL which is not an original URL.
I tried detecting refresh page with a cookie, hidden filed but it is not working.
window.onload = function() {
document.cookie="PR=0";
var read_cookies = document.cookie;
var s = read_cookies;
s = s.substring(0, s.indexOf(';'));
if( s.includes("1"))
{
window.location.href = "https://www.google.com";
}
else{
document.cookie="PR=1";
}
loadURL();
};
function loadURL()
{
document.cookie="PR=1";
document.getElementById("visited").value="1";
var str="abc/b cd";
str=str.replace(/ /g, "-");
history.pushState({},"",str);
}
when user is refreshing the page I need original URL on that time.
This might be helpful. But you need control over the pushed url.
// this goes to your 'original' url
window.addEventListener('beforeunload', function (event) {
sessionStorage.setItem('lastPage', window.location.href)
}
// page with your pushed url
if (sessionStorage.getItem('lastPage') === 'PAGE_YOU_DONT_WANT_TO_BE_REACHABLE_DIRECTLY') {
window.location = 'PAGE_YOU_WANT'
}
I'm interested what the use case for this is. As far as my knowledge goes you can't suppress the refresh event completely.

twitter share button quirk

Link to my in codepen: codepen.io/neel111/pen/dRBQNY?editors=1010
When the tweet button is clicked then it redirect to the page to tweet in the twitter, with a preselected text to tweet.
The JavaScript code used there is given below just for a quick look:
//-------------quotes--------
(function(){
window.addEventListener("load", makeRequest);
function makeRequest(mk){
document.getElementsByClassName("buttonQ")[0].addEventListener("click", makeRequest);
function reqListener(rl) {
if(httpR.readyState === XMLHttpRequest.DONE) {
var quote;
if(httpR.status === 200) {
quote = JSON.parse(httpR.responseText);
document.getElementsByClassName("quote")[0].innerHTML = quote[0].body;
} else {
alert("There was a problem with the request!")
}
}
}
var httpR;
httpR = new XMLHttpRequest();
httpR.onreadystatechange = reqListener
httpR.open("GET", "https://quote-api.glitch.me/pull/1", true);
httpR.send();
}
//----------------------tweet-------------------
window.addEventListener("load", function() {
document.getElementsByClassName("buttonT")[0].addEventListener("click", tweetEvent);
})
function tweetEvent(twt) {
//twt.preventDefault();
document.getElementsByClassName("quote")[0].normalize();
var tweetBody = document.getElementsByClassName("quote")[0].childNodes[0].nodeValue;
var URLBase = document.getElementsByClassName("twitter-share-button")[0].getAttribute("href");
var URLExtended = URLBase + "?hashtags=quotes&text=" + encodeURIComponent(tweetBody);
document.getElementsByClassName("twitter-share-button")[0].setAttribute("href", URLExtended);
}
})();
Quirk:
when the tweet button is clicked for the first time after the page is loaded/refreshed then the preselected text in the redirected page to tweet is
Preselected_text(quote)_from_the_main_page #tweet
But after the first click, everytime the tweet button is click the preselected text in the redirected page to tweet is
Preselected_text(quote)_from_the_main_page?hashtags=quotes #quotes
Where i am doing wrong?
So I think the problem is that you are modifying the href of the anchor tag and inserting the modified href into the dom. What I would do instead is to get rid of the in the button and build the url like you are but instead of modifying something in the dom just call window.open(extendedUrl);
Something like this should get you started:
window.addEventListener("load", function() {
document.getElementsByClassName("buttonT")[0].addEventListener("click", tweetEvent);
})
function tweetEvent(twt) {
//twt.preventDefault();
document.getElementsByClassName("quote")[0].normalize();
var tweetBody = document.getElementsByClassName("quote")[0].childNodes[0].nodeValue;
var url = "https://twitter.com/intent/tweet?hashtags=quote&text="+encodeURIComponent(tweetBody);
return window.open(url);
}
})
As you can see I have simplified the url building and then passed the resulting url to window.open which will open the url in a new window/tab (depending on user preference in their browser... find more on that here).

Javascript Queue commands

I have a Tab widget set up on my website using JQuery 1.7.2 and JQuery UI 1.10.3.
I have written a JavaScript that parses the hash part of a URL in order that I can open a tab, load content into a div and scroll to a named anchor.
I can get the tab to open and content to load fine, however, scrolling to the anchor is proving to be a real pain.
I can get it to work if I trigger an alert before the scroll to the anchor (forcing you to click 'OK', but if I disable the alert (which I want to), it doesn't work.
I am guessing that it has something to do with waiting for the functions to finish processing first? But I'm quite inexperienced with JavaScript so would appreciate any help anyone could could give.
URL example: http://www.mysite.com/abc.html#tab=tab-3&#srv=includes/xyz&#anc=myanchor
My JavaScript is as follows:
$(document).ready(function () {
var parts = location.hash;
parts = parts.split('&'); // Hash parts of URL.
for (var i = 0; i < parts.length; i++) // Loop to separate variables.
{
if (parts[i].substr(1, 4).toUpperCase() == "TAB=") {
var tab = parts[i].substr(5).split("-").pop() - 1
} // Tab no. part from tab name.
if (parts[i].substr(1, 4).toUpperCase() == "SRV=") {
var srv = parts[i].substr(5)
} // Path to content to load.
if (parts[i].substr(1, 4).toUpperCase() == "ANC=") {
var anc = parts[i].substr(5)
} // Named anchor to locate.
};
// Tab found in URL so we'll check it exists and open it.
if (tab == -1) // Tab not found?
{
tab = 0 // Default to 1st tab if not.
};
$("#tabs").tabs("option", "active", tab); // Select the tab.
// Load content if provided in URL.
var href = $('.list li a').each(function () {
var href = $(this).attr('href');
if (srv == href.substr(0, href.length - 5)) {
var toLoad = srv + '.html .maint_content';
$('.maint_content').load(toLoad)
}
});
// Load content when selected from list.
$('.list li a').click(function () {
var toLoad = $(this).attr('href') + ' .maint_content';
$('.maint_content').fadeOut('normal', loadContent);
$('#load').remove();
$('.maint_content').fadeIn('normal', loadContent);
$('#load').fadeIn('normal');
window.location.hash = $(this).attr('href').substr(0, $(this).attr('href').length - 5);
function loadContent() {
$('.maint_content').load(toLoad, '', showNewContent());
}
function showNewContent() {
$('.maint_content').show('normal', hideLoader());
}
function hideLoader() {
$('#load').fadeOut('normal');
}
return false;
});
// Scroll to locate anchor.
//alert(anc);
$('html, body').animate({
'scrollTop': $('#' + anc).offset().top
}, 1000);
});
Thanks
I'm assuming the anchor you want to jump to is in the loaded content?
If so, just add a callback to the ajax call and do the jump there:
$('.maint_content').load(toLoad,'',showNewContent()).done(function () {
window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-5);
});
You are ajaxing the content of the div. This means it is loading asynchronously. The animate function is thus called before the loading of the content has finished, and the anchor you are looking for is not yet there.
In order to fire the animation when the loading is complete, you can pass a function to .load()
$('.maint_content').load(toLoad,'',showNewContent());
so you allready got that: showNewContent is fired when the loading finishes.
So all you have to do is move your animation line to the end of that function.
function showNewContent()
{
$('.maint_content').show('normal',hideLoader());
$('html, body').animate({'scrollTop': $('#'+anc).offset().top}, 1000);
}

How to auto-open photo in Colorbox only when it's specified in URL?

This code gives each Colorbox image an URL (domain.com/#image). This can then be copied and pasted by user to open the wanted photo automatically when entering the site with that URL.
Everything works as intended but somehow it also auto-opens the first image on the site even when there is no #image at the end of the URL. How should I change this code that it will only auto-open the image when there is #image in the URL?
Thanks!
Code:
jQuery(function (){
var id, group;
group = jQuery("a[rel='lightbox[63]']").colorbox({onComplete:function(){
// Get the image URL
with_ext = (this.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1];
// Get the image url without the extension
without_ext = with_ext.substring(0, with_ext.lastIndexOf("."));
// Redirect
window.location.hash = without_ext;
}, onClosed: function(){
location.hash = '';
}});
id = location.hash.replace(/^\#/, '')+".jpg";
group.filter('[href$="'+id+'"]').eq(0).click();
});
Ok got it working.
If anyone else needs this kind of function here it is:
jQuery(function (){
var id, group;
group = jQuery("a[rel='lightbox[63]']").colorbox({onComplete:function(){
// Get the image URL
with_ext = (this.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1];
// Get the image url without the extension
without_ext = with_ext.substring(0, with_ext.lastIndexOf("."));
// Redirect
window.location.hash = without_ext;
}, onClosed: function(){
location.hash = '';
}});
if(window.location.hash) {
id = location.hash.replace(/^\#/, '')+".jpg";
group.filter('[href$="'+id+'"]').eq(0).click();
} else {
return;
}
});

Categories