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).
Related
I have a page where there is a form which is used to Add / Edit Addresses.
In the right section of the page, there is a saved address Which has Edit link and it gives call to the same page URL with adding a new parameter say "billingID.XXXXX".
After clicking on this link, page is re loaded with the default address data auto filled.
I need this to happen on the first time load. I tried triggering click event on this Edit link on load, but I suppose it is not allowed by jQuery.
What are the other options I have with jQuery / javascript to add this URL parameter on load of page.?
You could try the Javascript History API.
https://developer.mozilla.org/en-US/docs/Web/API/History_API
It depends on what you want to do, I didn't understand you quite clear.
If you need the page to be reloaded and show the page by url, you can get 'href' value by jquery and then call window.location = $('.mylink').attr('href') + '?billingID.XXXXX';.
If you just want to replace url in browser panel, you can use History API as Kahuna suggested. E.g. you can call
window.history.replaceState(null, document.title, window.location.path + '?helloworld=1');
but then you have to update the page contents by yourself, using JS and jQuery.
you can try this:
if(window.location.href == 'requestd page href'){//http://localhost/test/test.php
window.location.href += "?billingID.XXXXX";
}
I'm looking for a way to change the hash url automatically. (no page reload)
The reason I want it is this:
I'm using a pop login / registration form that only initially opens the login portion. You can only get to the registration portion after clicking the login. So, when the user clicks the http://website.com/#modal-login from a certain link, I'd want it to redirect to http://website.com/#register.
Currently it is directly going to the #register. Is there a way to change the hash url after user clicks on login?
No need to use jQuery
document.getElementById("modal-login").onClick = function () {
window.location.hash = "register";
}
For example, try pasting this into your browser's JavaScrtipt console, then click on your question text.
document.getElementById("question").onclick = function() {
window.location.hash = "footer";
}
If you really want to use jQuery for some reason
$('#modal-login').click(function(event) {
event.preventDefault();
window.location.hash = "register";
});
Edit:
Your question isn't about hash locations in general, but how this modal plugin that you're using works. The following was determined by reading the source to the plugin, found here:
http://demo.pressapps.co/plugins/wp-content/plugins/pressapps-modal-login/js/modal-login.js?ver=1.0.0
http://demo.pressapps.co/plugins/wp-content/plugins/pressapps-modal-login/js/modal.js?ver=1.0.0
Here's what you need to execute to get your desired behavior
$('.your-register-button-class').click(function(e) {
/* We expect plugin's click handler to fire in addition to this one. */
$(".modal-login-nav[href='#register']").click();
});
I'm assuming that the element with .your-register-button-class also has attribute data-toggle="ml-modal".
I have a code that after clicking on a link ('#versionPageFromProdLink'), will redirect the page to the index page. The index page has that contains the content. I want to hide this after the page is redirected and show the next div that i have ().
The page is redirected however the jQuery function after the window.location.replace( url ); line is not called.
How will I be able to redirect and call the jQuery after page redirection?
Code:
jQuery( '#versionPageFrmProdLink').click( function(){
window.location.replace( url );
// jQuery code below is not called, <div id="versionMainContent"> is not hidden
jQuery(".versionMainContent").hide("fast", function(){
jQuery( ".versionProductContent" ).show();
});
});
As stated, the location.replace means the code "after" it won't execute. What you will need to do, is append a hash "index.html#divCode" or some such (you could also use a query string in this case) and then detect that onload / on document-ready for the index page, then update the hide/show status there.
This is fundamentally impossible.
Once you navigate to a different page, the previous page, including all of its Javascript, is gone.
You must handle the secondary executation after the redirect in the page you are redirecting to.
Example:
Page 1
jQuery( '#versionPageFrmProdLink').click( function(){
window.location.replace( url );
}
Note during redirection you can pass a query string in the URL to check a condition in the next page.
Page 2
Now that you redirected to the next page. You can place a document.ready function and run what is needed.
$(document).ready(function () {
jQuery(".versionMainContent").hide("fast", function(){
jQuery( ".versionProductContent" ).show();
});
Your design is the problem. Redirecting stops the flow of execution. You can use ajax to make a server call and continue execution.
Or, if you prefer you can perform a redirect and pass a URL parameter like ?hideVersionMainContent=true and perform the hide server side.
There are other ways to accomplish the task, but that should give you a few ideas.
The code after your location.replace operates on the page that you're leaving (if it is ever run at all; changing the location navigates away from the page and may well terminate your code right there).
You'll need to pass the information to display to the new page, and have code on the new page fill in the stats. There are lots of ways to do that:
On the query string
Via web storage (sessionStorage would probably make sense)
Cookies (but don't, it's not what they're for)
hi here is the problem: my url is like this
http://somesite.com?theSearch=someword&a=b&c=d
on this page search results are displayed and on this page i have put the functionality of ajax search i.e. the results are updated without the page reload but the problem is if the user clicks on any link on the page and then presses the back button he results on the page page with the search results of "someword" not the new word typed (i mean the word for which the ajax results were updated) the client complains it and i need to fix it anyone have a solution?
i am using jQuery
You can't change the location.href without a new load. What you can do is set the hash.
Every time you make a search change the hash
function doSearch(searchword) {
location.hash = searchword;
//your search code
}
Now the hash will refer to the latest search. And then add this code to "override" the get parameter ?theSearch=.
$(document).ready(function() {
if(location.hash.length>0) {
doSearch(location.hash);
}
});
Its not a nice solution since you will load 2 search results, but it will work.
You can try Sammy. It utilizes the URL hash (#) so you can create single page applications that still respond to the back button in your browser, just like facebook. And it runs on jQuery.
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