On my page, a content container holds different information depending which list item was clicked (news, video, blog, etc.)
This is achieved by loading in html snippets with jQuery's load method like this:
$('#container').load('blog.html'); // file from my domain
After the load, I can update the URL using this:
window.history.pushState("www.mysite.com", "mysite", "/blog");
Or change hash:
window.location.hash = "blog";
When the link is visited directly, this causes an error because there is no knowledge of such a page on my host. After the AJAX load, I'm wondering what the best way would be to make the current state of the page shareable ( I send the link to someone, and when they visit it, they see the state of the page as it was when I shared the link)? The link would be something like: www.mysite.com/blog.
The AJAX load:
$('li a').on('click', function(){
var file = this.id;
$('#container').load(file +'.html');
// window.history.pushState("www.mysite.com", "mysite", "/" + file); or..
// window.location.hash = file;
return false;
});
P.S. I would like to avoid using php for the sake of simplicity, but am open to all suggestions.
Well, if you use the hash, as you already state in OP, you should have no errors when you visit it directly. ( example: www.mysite.com/#blog )
On load javascript can check if a hash is set, and do the necessary ajax calls again to serve the page from a direct link. (PHP cannot see the hash by the way, so using only the hash, will not be controllable from PHP server side.)
$.ready( function() {
if (window.location.hash == "blog") $(#container).load("blog.html");
});
Using pushState (example: www.mysite.com/blog ) is a different story... That one would need you to create a .htaccess that will rewrite to (for example) the index.php. Index.php could then have javascript-logic that looks at the requested url, to load the desired content again with Ajax. (Or even without ajax, if you do it in PHP)
javascript (after configuring .htaccess to rewrite to the file holding this javascript):
$.ready( function() {
if (window.location.pathname == "/blog") $(#container).load("blog.html");
});
or in php (after configuring .htaccess to rewrite to the file holding this php):
<div id="container">
<?php
if ($_SERVER["REQUEST_URI"] == "/blog") {
include("blog.html");
}
?>
</div>
On page load, check for window.hash. If it is not empty, then do the same thing that you do when an <a> is clicked in your <ul>. But to not to reinvent the wheel, have a look at javascript routers, for example crossroads.js.
Related
Please I have multiple HTML pages with each having a separate .js file. I want to recognize each page by URL and load each implementation on page load. I understand I can check load event on HTML element using jQuery like
$( "#result" ).load( "ajax/test.html" );
As specified here. How do I extend that to the pages? I want to execute a jQuery/AJAX load event on each of my HTML pages to check few things like user status or authorization. Example to check if user is logged in, then proceed and execute other jQuery codes, otherwise redirect user to login page.
In page header do a authentication check and redirect user to login page.
$(function() {
$('#result').load('auth/test', function( response, status, xhr ) {
if (response == 'guest') {
window.location = 'auth/login';
}
});
You can either put this code in separate file and include the file in every page or use some template hierarchy to achieve this.
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.
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;
});
I am using ajax post requests for doing paging on a feed in my site. When getting the post request data I am reforming the page by clearing previous data and rendering the new data that came from the request. I want to be able to change the URL as well so saving the new page link will get the user to the current page.
Example:
User on page example.com/feed - seeing content of page #1
User clicking to get to page #2 -> ajax post is send and data on the page is changed using js (no refresh)
URL is still example.com/feed but the content is of example.com/feed?page=2
How can I set the URL to point to the new page without triggering a refresh (no redirect) ?
I am using Nodejs + express.
I understand you are aiming at a single page application.
While keeping the url is nice, note you might want distinct urls for directly accessing different parts of your application. Still, you can load content with AJAX and keep a smooth application. The way to go is using the hash part of the location.
The Sammy.js framework gives you a nice base to build upon, you can try it out.
You can use history pushstate but some browsers does not support.
history.pushState({id: 'SOME ID'}, '', 'myurl.html');
And don't forget about window.onpopstate, it pops if user clicks back button.
Redirect the user to an anchor point.
Page 2
And in your document.ready:
if (window.location.hash.length > 1){
var pageNumber = window.location.hash.substring(1);
loadPage(parseInt(pageNumber));
} else{
loadPage(0);
}
I don't believe it is possible to change the query part of the URL without triggering a refresh (probably due to security issues). However you may change the anchor and use an event listener to detect when the anchor is being changed.
//Listener
$(window).on('hashchange', function() {
if(loaction.hash.length > 1) {
//The anchor has been changed.
loadPageWithAjax("example.com/feed.php?page=" + location.hash.substring(1));
} else {
//Load standard page
...
}
});
Change the anchor to load new feed
Page 2
Remember to not use an anchor that is used as an id, since this makes the browser scroll to that element.
I am new to Jquery mobile.
I am trying to get Sliding effect when i navigate to another page say # display2 from thie below code.
but i am not able to get slide effect.
If I remove the rel="external" i am able to slide but on the #display2(page whihc i would navigate to),the query string values are returned as null.
so if i put rel="external" the parameters are passed to #display2 but slide transition not working.
if i remove re="external" slide works but the querystring parameters are returned null.
can you please let me know is there a way where both of them work together.
('#display').on('pagebeforeshow', function () {
// $(this).find('[data-role=header] .ui-title').text(json.getLOBXMLResult[currentItem].FolderName);
$.ajax("AppstoreWS.svc/getLOBXML", {
beforeSend: function (xhr) {
$.mobile.showPageLoadingMsg();
},
complete: function () {
$.mobile.hidePageLoadingMsg();
},
contentType: 'application/json',
dataType: 'json',
type: 'GET',
error: function () {
//alert('Something awful happened');
},
success: function (data) {
result1 = data.getLOBXMLResult;
$('#categoryList').children().remove('li');
$.each(result1, function (index, output) {
$('#categoryList').append('<li>' + output.FolderName + '</li>');
});
$('#categoryList').listview('refresh');
}
});
});
Part 1 - why rel=external worked & other options
The reason why rel=external works with no transition is because this expects the browser to open an external page and therefore, disable ajax. To counter-effect this, you've got numerous options :
By using Single page template
You could make your two pages into a single page. This is called a single page template and your second page's reference would be #page2 (or any name you'd give as the ID). This is how it'd look like :
<div data-role="page" id="page1">
<!--Stuff in page 1-->
</div>
<div data-role="page" id="page2">
<!--page 2 stuff-->
</div>
Advantages
The DOM can leverage the power of ajax driven navigation.
This would make partial loading, script loading easy, as you'll need to refer all this only once.
Data-transfer between pages is very simple. You'll just have to store the data in you need in a global variable or in the data property of the #page2, and retrieve it in the pageinit or pageshow (or any event) of the second page.
Transitions, etc will work.
There will be no page refresh.
Disadvantages
If the HTML content of the two pages are large, it'll be difficult for maintenance.
By using rel=external
As you might have seen, rel=external can be used only when a page refresh is absolutely needed. Its upto the user's choice. If an a tag is marked with rel=external it means the browser will treat it as an external link, and will ignore jQuery Mobile's ajax navigation system.
By referring all the scripts of page 2 in page 1
Generally, to be able to use page transitions, you must use ajax system of navigation in jQM. So the general behaviour of ajax is as follows :
page1 will request for page2 in page2.html.
The <body> of page2.html alone is taken from page2.html.
The <head> section( which might contain your scripts, which might have your query-string logic) will be ignored.
So to change this, you can refer to page2's scripts in page1.html's head so that these scripts will be loaded and ready when jQM's ajax system pulls the body of page2.html.
<script src="jqm.js"></script>
<script src="page1.js"></script>
<!--page 2 scripts-->
<script src="page2.js"></script>
Advantages
Your transitions will be working properly.
The common scripts will not be referred to multiple times, hence much faster loading times.
Query strings will also work
Disadvantages
If the two pages have very little in common, you'll end up having unwanted scripts in your first page.
What if you have more than two pages? What if you have 10 pages? Will you refer to all 10 pages' scripts in page1. I dont think thats the way.
By referring to page2 scripts inside "data-role=page" section of page2.html (recommended)
This will bring the scripts along with the page when ajax brings it in. This will also work with query strings. This will look something like this :
<div data-role="page" id="page2">
<script src="page2.js"></script>
<!--- your html-->
</div>
Advantages
The scripts pertaining to a particular page are restricted to within that page.
Transitions will work.
Query strings will also work
Part 2 - alternative to query string
The reason I'm saying this because Query strings are archaic technology, because at that time, there was no way to store to data. They're also insecure because user can see the data you send over the URL. You must consider using something like localStorage. I'm not saying you must NOT use query strings. It's just that there are better options available for mobile data storage. See this link for more info about how you can use this localStorage. Also, see this for all the options you have. Now, looking at your query string :
platform=' + output.FolderName + '&sid=test
This could easily be made into an object. So in the click function of the anchor tag inside <li>,
$(document).on("click", "li a", function(e) {
//stop default action.
e.preventDefault();
//take the href; Im assuming its page2.html?platform=outputFolder&sid=test
var params = this.href.split("?");
//now params[0] = page2.html
//param[1] = platform=outputFolder&sid=test
//set this in localStorage
localStorage["page2params"] = param[1];
//change to page2.html
$.mobile.changePage("page2.html", { transition : slide });
})
Then, in the page2.html's pageinit method, you could retrieve it for your use :
//assuming you have a page with page2 as id in page2.html
$(document).on("pageinit", "#page2", function() {
var params = localStorage["page2params"];
//do anything you want with params.
});