jQuery: Reload a DIV which was already loaded by AJAX (without url)? - javascript

I load a div by a simple
$('#thediv').load("theurl/param1/param2/param3");
The params differ - and I grab them from different points - depends on where the user clicks. (Different filter options..)
Now I'm searching for a simple way to reload this content with the url it was actually loaded - to avoid searching for the right filter params at this place. It is possible?

jQuery will not "save" the source of information on its own, but it is possible to specify it manually using the .data() method alongside the initial .ajax()
This means during the initial load, you can associate a URL with a div by saying something like .data("source-url","MY URL GOES HERE")
After that, you can look up that information the next time you want to reload it by using .data("source-url")
For Example:
function reloadDivs() {
// Look up all of the divs that we might want to reload
$("div.reloadable").each(function(i,el) {
// For each div, check to see if the source-url was set
// If it was set, re-run the ajax call
var $el = $(el);
if($el.data("source-url")
$el.load($el.data("source-url"));
});
}
$(function() {
// Set the initial source, change mypage.html to your actual source
$("#example-div").data("source-url","mypage.html");
$("#refreshbutton").click(reloadDivs);
});
Hope this helps!

Related

remember most recent click

So I want to be able to have a different styling for a link after you go to the page it's clicked on. I have been using the following code:
$(document).ready(function(){
var url = document.URL;
function contains(search, find) {
return search.indexOf(find) !== -1;
};
$('#topbar a').each(function(){
var link = $(this).attr('href');
var answer = contains(link,url);
if(answer === true){
$(this).addClass('check');
}
else{
$(this).addClass('nocheck');
};
});
});
This goes through the links in my navigation bar and checks if it's on the same page as the link, and it works, but I can't use it in one specific case: Random.
I have a link that generates a random page from the pages I have, so it does not have a specified link as it links to a function to randomly generate the page (note: I cannot change the function or access information from it).
So how can I detect that the random link was clicked previously so i can give it the .check class
If i understand your question correctly, your function does not work for the randomlink because this has a href like http://mysite.com/random, but the server will actualy redirect you to a different page, like http://mysite.com/about-me, and therefore the url of the active page does not match the href of the random button, and it will not get the active state.
One could argue if you would want it to get the active state, cause clicking it again would not (likely) bring you to the same page, but that is besides the question.
I can see to ways to solve this.
server side:
In stead of redirecting to ie. http://mysite.com/about-me in the random function, you could also redirect to http://mysite.com/about-me?random. By adding this get variable, you should not change the behaviour of the link (unless you have some very strict controller, or that variable is actually used, but that is unlikely). You could then detect with javascript if that variable is present in the url, and then activate the random button.
Something like this:
$(document).ready(function(){
var url = document.URL;
// check for random
if (url.indexOf('?random') >= 0) {
$('#topbar a.random').addClass('check');
}
// check all other
$('#topbar a:not(.random)').each(function(){
if($(this).attr('href').indexOf(url) >= 0){
$(this).addClass('check');
}
else{
$(this).addClass('nocheck');
};
});
});
cookie:
If you do not have acces to the server side random controller, you could do it entirely with javascript, by the use of a cookie (the only way I know to make a variable persist trough page requests).
On click of the random button, you would first set a random cookie to true with javascript, before letting the actual link do it's thing. On entering the page, you could then do a similar check as in my previous option, but in stead of the url you check if the cookie is tre. If so, you change it to false (so on the next page request the random button will not be active again) and set the randombutton to active.
As I believe the first solution is to be preferred (cookies should only be used as a last resort, they are sent on every page request, which means extra data, and your user might have cookies disabled, or there might be laws against using cookies, so the function could not always work), I will not write the javascript yet. Feel free to ask if you prefer this solution and need further help however.

How to create the breadcrumb and the shifting view effect similar to Github

Clicking a breadcrumb link in github will trigger the directory view area to transition to the subdirectory . What is the best way to achieve this effect. I am using asp.net mvc , jquery, jquery ui, and a jquery layout plugin ( http://layout.jquery-dev.net/ ui layout )
Shoud I abandon the layout plugin ?
Well, you can start by using the unique url pattern. To make this sound a little familiar, let's take for example twitter:
#searching "stackoverflow"
https://twitter.com/#!/search/stackoverflow
the hash part is the one after (and including) "#". using window.location.hash gets it for us. then use string.replace() to remove #!/ and end up with:
search/stackoverflow
then if we store this value as a variable and do string.split('/'), which is split the value per /, we are returned with this:
array = ['search','stackoverflow'];
now it looks more like a breadcrumb which we can use to build. if you were in twitter, it would be more like:
site / search / stackoverflow
and for each breadcrumb link, just append further. if you have segmented urls, it's pretty easy to build the links:
site = mysite.com
site/search = mysite.com/search
site/search/stackoverflow = mysite.com/search/stackoverflow
for the sliding part, you need to pick up the "onhashchange" event which detects the changes to the value of the hash. The event always happens when you click a link that has href="#somevalue" - note the href having "#". you also notice that the page does not go anywhere (that's where AJAX magic comes to play later).
for modern browsers, you can detect hashchange using jQuery or plain JS:
$(window).on('hashchange',function(){
//do whatever you want when the hash changes
});
//or
window.onhashchange = function(){
//do whatever you want when the hash changes
}
for older browsers, you have to set a timer that checks the previous vs current value of the window.location.hash
(function timer(prevHash){
var currentHash = window.location.hash;
if(prevHash !== currentHash){
//do whatever you want when the hash changes
}
setTimeout(function(){
timer(currentHash);
},1000);
}();
the sliding effect can be achieved using jQuery .animate(). you can load the new page via AJAX (depending on the page you determined using the parsed hash), append the loaded page, slide the contents, and boom! you are done. It's pretty easy for everyone to make if they know the gears that make the clock turn.

how to refresh the browser after the page is loaded

I have a scenario to refresh the browser after the page is loaded for first time or one time.
Because the data is not showing properly when the pages is loaded,and when i refresh the browser it is showing.I don't know the reason.
Many Thanks
So you only want the browser to refresh once? Do something like this.
window.onload = function(){
if(!document.location.hash){
window.location = "#loaded";
}
}
or jquery
$(document).ready(function(){
if(document.location.hash){
window.location = "#loaded";
}
});
But in all honesty this is just a temporary solution. As much as you try to cover it up with quick fixes. I guarantee it will come back to haunt you. Well written and structured code will last a lifetime and can always be reused on future projects.
Invariably, you're going to have to use some JavaScript. What you want is for your refresh code to run when the page is completely loaded. You could use the HTML onload event, but there are problems with this (e.g. it will fire before any images are loaded). I would suggest using JQuery's ready() event, if you want to be sure it fires after the entire page is loaded.
Example:
// NOTE: This will only work with JQuery loaded.
$(document).ready(function(){
location.reload(true);
});
Making this only fire on the first page load is a bit more tricky. You could add an anchor suffix to the URL to keep track of whether you've refreshed the page yet or not, and then only refresh if it is not present in the URL:
$(document).ready(function(){
if(location.hash != "#")
{
// Set the URL to whatever it was plus "#".
// (The page will NOT automatically reload.)
location = "#";
// Reload the page.
location.reload(true);
}
});
Alternatively, you could use the query string, since this will automatically refresh the page when changed:
$(document).ready(function(){
var marker = 'r'; // 'r' is for "refreshed"
if(location.search != "?"+marker)
{
// Set the URL to whatever it was plus "?r".
// (This will automatically force a page reload.)
location = "?"+marker;
}
});
Caveat: With either of these samples, if your user bookmarks the page after the "#" or "?r" tag has been added to the URL, the page won't refresh when they revisit the page. If you want it to be bulletproof, you might have to use a cookie instead.

Executing JQuery after page load only after clicking a specific link

I have a link in my app that when clicked, leads to another page. I want to execute some JQuery on this new page after it loads, but only if that specific link is clicked to get to the page.
I have this JQuery:
$('#new_to_topics').click(function(){
$(document).ready(function() {
$('#topic_guidelines').slideDown('normal');
$('#topic_guidelines').addClass('on');
});
});
where #new_to_topics is the id of the link that leads to the new page and
$('#topic_guidelines').slideDown('normal');
$('#topic_guidelines').addClass('on');
is the JQuery code I want to execute on that new page. However, this does not work. How should I do this?
You could pass a location hash to the new page, and then conditionally run some javascript based on that hash.
If my link was to mynewpage.html#fromXlink (this would show in the address bar)
My javascript on mynewpage.html could be:
$(document).ready(function() {
if (location.hash == '#fromXlink') {
$('#topic_guidelines').slideDown('normal');
$('#topic_guidelines').addClass('on');
}
});
You could add a variable to the query string i.e. somepage.aspx?fromthislink=true
and then pick that up in jquery.
This shows how
If it cam from that link then fire off your jquery.
You can use window.name to pass data to the target page (although I would prefer passing data in the hash, if possible).

Force page reload with html anchors (#) - HTML & JS

Say I'm on a page called /example#myanchor1 where myanchor is an anchor in the page.
I'd like to link to /example#myanchor2, but force the page to reload while doing so.
The reason is that I run js to detect the anchor from the url at the page load.
The problem (normally expected behavior) here though, is that the browser just sends me to that specific anchor on the page without reloading the page.
How would I go about doing so? JS is OK.
I would suggest monitoring the anchor in the URL to avoid a reload, that's pretty much the point of using anchors for control-flow. But still here goes. I'd say the easiest way to force a reload using a simple anchor-link would be to use
where in place of $random insert a random number (assuming "dummy" is not interpreted server side). I'm sure there's a way to reload the page after setting the anchor, but it's probably more difficult then simply reacting to the anchor being set and do the stuff you need at that point.
Then again, if you reload the page this way, you can just put myanchor2 as a query parameter instead, and render your stuff server side.
Edit
Note that the link above will reload in all circumstances, if you only need to reload if you're not already on the page, you need to have the dummy variable be more predictable, like so
I would still recommend just monitoring the hash though.
Simple like that
#hardcore
an example
Another way to do that is to set the url, and use window.location.reload() to force the reload.
<a href="/example#myanchor2"
onclick="setTimeout(location.reload.bind(location), 1)">
</a>
Basically, the setTimeout delays the reload. As there is no return false in the onclick, the href is performed. The url is then changed by the href and only after that is the page reloaded.
No need for jQuery, and it is trivial.
My favorite solution, inspired by another answer is:
myanchor2
href link will not be followed so you can use your own preference, for example: "" or "#".
Even though I like the accepted answer I find this more elegant as it doesn't introduce a foreign parameter. And both #Qwerty's and #Stilltorik's answers were causing the hash to disappear after reload for me.
What's the point of using client-side JS if you're going to keep reloading the page all the time anyways? It might be a better idea to monitor the hash for changes even when the page is not reloading.
This page has a hash monitor library and a jQuery plugin to go with it.
If you really want to reload the page, why not use a query string (?foo) instead of a hash?
Another option that hasn't been mentioned yet is to bind event listeners (using jQuery for example) to the links that you care about (might be all of them, might not be) and get the listener to call whatever function you use.
Edit after comment
For example, you might have this code in your HTML:
example1
example2
example3
Then, you could add the following code to bind and respond to the links:
<script type="text/javascript">
$('a.myHash').click(function(e) {
e.preventDefault(); // Prevent the browser from handling the link normally, this stops the page from jumping around. Remove this line if you do want it to jump to the anchor as normal.
var linkHref = $(this).attr('href'); // Grab the URL from the link
if (linkHref.indexOf("#") != -1) { // Check that there's a # character
var hash = linkHref.substr(linkHref.indexOf("#") + 1); // Assign the hash to a variable (it will contain "myanchor1" etc
myFunctionThatDoesStuffWithTheHash(hash); // Call whatever javascript you use when the page loads and pass the hash to it
alert(hash); // Just for fun.
}
});
</script>
Note that I'm using the jQuery class selector to select the links I want to 'monitor', but you can use whatever selector you want.
Depending on how your existing code works, you may need to either modify how/what you pass to it (perhaps you will need to build a full URL including the new hash and pass that across - eg. http://www.example.com/example#myanchor1), or modify the existing code to accept what you pass to it from you new code.
Here's something like what I did (where "anc" isn't used for anything else):
And onload:
window.onload = function() {
var hash = document.location.hash.substring(1);
if (hash.length == 0) {
var anc = getURLParameter("anc");
if (anc != null) {
hash = document.location.hash = anc;
}
}
}
The getURLParameter function is from here
If you need to reload the page using the same anchor and expect the browser to return to that anchor, it won't. It will return to the user's previous scroll position.
Setting a random anchor, overwriting it and then reloading seems to fix it. Not entirely sure why.
var hash = window.location.hash;
window.location.hash = Math.random();
window.location.hash = hash;
window.location.reload();
Try this its help for me
<a onclick="location.href='link.html'">click me</a>
In your anchor tag instead of
click me
As suggested in another answer, monitoring the hash is also an option. I ended up solving it like this so it required minimal code changes. If I had asked the original question, I believe I would have loved to see this option fully explained.
The added benefit is that it allows for additional code for either of the situations (hash changed or page loaded). It also allows you to call the hash change code manually with a custom hash. I used jQuery because it makes the hash change detection a piece of cake.
Here goes!
Move all the code that fires when a hash is detected into a separate independent function:
function openHash(hash) {
// hashy code goes here
return false; // optional: prevents triggering href for onclick calls
}
Then detect your hash for both scenarios like so:
// page load
$(function () {
if(typeof location.hash != typeof undefined) {
// here you can add additional code to trigger only on page load
openHash(location.hash);
}
});
// hash change
$(window).on('hashchange', function() {
// here you can add additional code to trigger only on hash change
openHash(location.hash);
});
And you can also call the code manually now like
Magic
Hope this helps anyone!
Try this by adding simple question mark:
Going to Anchor2 with Refresh

Categories