Open tab based on URL - javascript

Information:
I have made a "tabs" type section to display all of my legal forms (https://get.goreact.com/legal/). I have given each individual tab an ID that populates in the URL. For example when I click "Privacy Policy" the URL changes to (https://get.goreact.com/legal/#legal|2).
Problem Trying To Solve:
The URL changes depending on what tab/button you click on. But if you try going that the URL directly (or a new tab) it doesn't open the correct tab/display the correct content.
What code do I need to add in order to have the URL "https://get.goreact.com/legal/#legal|1" and "https://get.goreact.com/legal/#legal|2" and so on open the respective tabs? I am new to JS and need some help.

You can use one short solution by using jQuery. After this, you don't have to add or remove any classes to any element.
$(document).ready(function(){
if( window.location.hash != "" ) {
$('a[href="' + window.location.hash + '"]').click()
}
});
Try this once

Related

cannot get react-autocomplete item selection to trigger location change

I am using https://github.com/reactjs/react-autocomplete for easy navigation in my webapp. My usage is similar to the example seen here: https://github.com/reactjs/react-autocomplete/blob/master/examples/async-data/app.js
I want the browser to open a certain url (in the current window) when the user selects an item of the autocomplete.
My code for this looks like this:
onSelect={(value, item) => {
const url = "/customer/" + item.id;
//alert(url);
window.location = url;}
}
When an item is selected in the autocomplete (via cursor keys + enter key), the browser does not open the new url, which would be expected. Instead, the browser reloads the current page and adds a question mark at the end of the url.
The weird thing is: When I place an alert(url) before the window.location assignment, it works (the browser shows the alert first and then indeed opens the new url).
Any ideas what I am doing wrong? Thanks!
Ok found it, the react component was contained also a from. So hitting enter triggered a form submit in addition to triggering the onSelect callback.

How to make link with hidden URL

I was wondering whether it was possible to make a link with <a> tags that doesn't display its URL?
Put into other words, I would like a piece of HTML that either hides or obfuscates the URL that it links to.
I have found this StackOverflow question, but I'd prefer that the link would work in all browsers (not just chrome) and was not a popup. I already have access to jQuery, Bootstrap and PHP 5.5.
Any help would be appreciated.
UPDATE: I feel this needs clarification. I do not want it to be visible in ANY way - i.e. this is a link that must NOT be shared, so I cannot simply use redirects and just hide the URL when it is hovered over - I do not want it visible in the source code either. Sorry for any inconvenience :(
Thanks,
ICT
You can capture the link in a closure to hide it, then point the window there when the <a> is clicked, for example
function hideLink(anchor) {
var href = anchor.getAttribute('href');
anchor.removeAttribute('href');
anchor.className += ' pseudolink';
anchor.addEventListener('click', function (e) {
e.preventDefault();
window.location.href = href;
});
}
window.addEventListener('load', function () {
hideLink(
document.getElementById('my_link')
);
});
.pseudolink {
color: blue;
cursor: pointer;
text-decoration: underline;
}
<a id="my_link" href="http://google.com">Hover over me</a>
It is not possible to completely hide the URL you are attempting to navigate to. The URL must be present in some form - such as the 'href' attribute of the <a> - tag to tell the browser where to navigate to.
However, it is possible to mask the URL with access to your server settings. Using a .htaccess file it is possible to redirect from one entered URL to another, whilst maintaining the entered URL within the address bar of the browser. There are many sources online that explain how to do this.
Simply handling each link using some logic within a PHP file may be suitable to hide the link in the source. For example, you could send every link to handler.php and specify a value for which page to navigate to, ie handler.php?page=1.
handler.php would then contain something along the lines of:
<?php
if ($_GET['page'] == 1) header('Location: /where/you/want/to/go');
if ($_GET['page'] == 2) header('Location: /where/else/you/want/to/go');
?>
This way, the user will not know where the link actually goes and (using the .htaccess settings) unaware of the URL they have navigated to.
You could use an url minifier like this one : https://goo.gl/.
<a data-link="some link here"></a>
$('a').on('click', () => {
window.location.href = $(this).attr('data-link');
});
User won't see the link while hovering it.

Detect which link was clicked with javascript that got user to specific page

Been searching on the web for a solution, but couldn't find anything, so maybe it's not possible, although I hope it still is.
What Im trying to do is detect the button (class or id) that was clicked when being redirected to another page on my site.
What I have is a portfolio page that contains a large amount of divs with different classes, so when someone clicks on a specific button on the homepage and gets redirected to the portfolio page, is it possible to detect on the portfolio page how the visitor got directed from. So detect which button got clicked.
no idea how to approach this, something maybe with if previous window.location last action find class or id.
Hopefully my question makes sense and someone can give me an idea if even possible.
I imagine it would rather be possible to do with php, but unfortunately server side languages are not an option in this case.
Thanks
Examples of methods you can use
add the information in the originating url - use location.search or location.hash depending on your choice of ? or #
Set a cookie (or use session/localStorage in modern browsers) in originating page and read it in the target page
Interrogate document.referrer (not always set)
You can't do it without either modifying the links (adding a query string or hash), or having code on the source pages (where the links are).
The former is pretty obvious: Just add a query string or hash (I'd use a hash) that identifies where the click came from, and look for the hash on the portfolio page. E.g., links:
Portfolio
Portfolio
and in the portfolio page:
var from = location.hash;
If you don't want to do that, and you can put code on those pages, it's easy: Add a click handler that sets information about the link in sessionStorage (very well-supported on modern browsers), and look for it in sessionStorage when you get to the portfolio page.
E.g.,:
$(document).on("click", "a", function(e) {
// Maybe check the link is going to portfolio, or refine the selector above
sessionStorage.setItem("linkFrom", this.className);
});
and then in the portfolio page:
var from = sessionstorage.getItem("linkFrom");
You can use window.localStorage to save the last id of the clicked element.
localStorage.setItem('last_clicked_id', id);
And then read it in the next page:
localStorage.last_clicked_id
Before running you should check for localStorage support:
if(typeof(Storage) !== "undefined") {
//localStorage code
} else {
//no localStorage support
}
this is how it works: the recent page or url is set on the URL parameters like a GET server request, but instead the client will receive it and parse it not the server. the recent page or url is on the "fromurl" parameter. on every page put this in (it's a javascript code):
function getURIparams(s) {
loc = window.location.href;
loc = loc.substring((loc.indexOf("?")+1));
loc = loc.split("&");
for (l = 0; l < loc.length; l++) {
lcc = loc[l].split("=");
if (lcc[0] == s) {
return lcc[1];
break;
}
}
}
next on every anchor link put this in href:
The Link to another page
after that, on every page execute this javascript:
from_url = getURIparams("fromurl");
the "from_url" variable will be the string variable of where the user clicked before it comes to that page.
if you are to lazy to put all those anchor one by one like this, do this work around but you need jquery for this. you dont need to put the parameter on the links for it to know where it comes from it will be automatically added by jquery.
$(document).on('click', 'a', function(e){
e.preventDefault();
window.location.href = e.target.href + "?fromurl=" + window.location.pathname;
});

URL change doesn't reload the document -> how to check the hash?

I have a div on my page (with set id) and a button that "opens"/"closes" it. By default this div is hidden (display: none).
Upon the click on the button I open/close the div and append or remove a hash tag to the url: window.location.hash = "#about_us_text"; or window.location.hash = ""; On each document load I check whether the hash tag is set so I can show the div right away if the URL was inputed with the hash tag:
if(window.location.hash == "#about_us_text") {
$("a[href='#about_us_text']").trigger("click"); //trigger the click event which 'slides down' the div
console.log("hash found");
}
This all works quite fine but there is a small problem I cannot resolve. If I open a new tab/window and I input the URL with or without the has, it works as intended. But if I open the page, let it load and then replace the URL within the same tab, the hash tag is not taken into consideration. E.g.:
I open www.mysite.com/index.html -> no hash, div doesn't show => correct
I replace the url in the same window/tab to www.mysite.com/index.html#about_us_text -> the page doesn't reload (document ready doesn't fire), div does not show despite the fact that it should.
Is there any way how to solve that the div is shown/displayed when the URL changes in the same window/tab? Thanks a lot!
I found this handy. original post is here
On - window.location.hash - Change?
$(window).on('hashchange', function() {
//.. work ..
});

jQuery Modals: URL poiting to an specific modal (routing)

I'm using plainModal (http://anseki.github.io/jquery-plainmodal/) plugin for displaying a set of modals in a page (http://codepen.io/Frondor/pen/xEBiA)
All the items are initializing the modals with no problems, but I need to share an URL like mywebsite.com/#some-modal so the page is loaded along with that modal active (#some-modal).
You can see my codepen above and try to enlighten me with some solutions.
I think I have to use some router script, but I don't have any idea about it. My site has to be purely static, html + js + css.
Although that "plainModal" plugin has some options about initialize method, I don't understand nor can't figure out the way to do it with URLs.
Thanks in advance!
You can check the URL for a hash and then open a modal based on the hash:
// does url have a hashtag?
if(window.location.hash) {
var hash = window.location.hash.substring(1); //Puts hash in variable, and removes the # character
$('#sample-style').plainModal('open', {
duration: 500}, 'close', {close: $.fn.slideUp});
console.log(hash);
} else {
// No hash found
}
Right now this opens $('#sample-style') - which is the same div you are opening for every other click. When you add new content for each item you can use the code $('#'+hash).plainModal('open'); // this opens <div id="{hash here}"></div> to open a div based on the hash.

Categories

Resources