As of now, on my page, the following html is working fine to trigger the following javascript function :
Link to other section
What I'd like to do is to have the javascript function triggered on page load when a specific variable is added to the URL. (Instead of having it as a link on the page)
For example, if url is www.mysite.com, page loads normally. If URL is www.mysite.com/?variable=1 , the script is triggered and user is redirected.
(I know there are other ways to redirect a user to another page, but I need to use this specific script, since the destination is dynamic from one type of user to another.)
I have very basic javascript knowledge and can't make the code I found here work : Triggering Script VIA URL . What they're doing is triggering a fancybox through URL variable. I believe that it's the same thing I want to achieve here. I'm just not to sure how to modify the code to go from "fancybox" to "redirectToOtherSection()"
var $j = jQuery.noConflict();
$j(document).ready(function() {
var url = window.location.href;
url = url.toLowerCase();
if (url.indexOf('globe=1') != -1) {
$j("a#fancy").fancybox({
'padding': 0,
'overlayShow': false // extra comma removed
});
}
}); // extra curly bracket removed
$j("a#fancy").fancybox({
'padding': 0,
'overlayShow': false // extra comma removed
});
They are using jquery, not sure if jquery is needed in my case?
Any help is much appreciated!
Thanks
based on what you've said you dont need jquery, try
var url = window.location.href;
url = url.toLowerCase();
if (url.indexOf('variable=1') != -1) { // where variable 1 is wqhats in you url
redirectToOtherSection();
}
Related
I want jquery to find and change the current URL you are visiting and load the new one. Lets say jquery is supposed to change the current "index.html" to "indexalt.html" on click and then load it. My idea is to use document.URL to get the current URL then slice off ".html" at the end and add for example "alt.html" to string. I'm very new to jquery and don't get it to work. There will be a lot of mistakes within my script probably:
$("#contact").on('click', function() {
var url=document.URL(str.slice(-7));
.load("url +"alt.html"");
I would really appreciate if anyone can tell me how to do it and how to write it down correctly in a whole. Thanks!
location.href returns the URL of the page. So, you can do this instead.
$("#contact").on("click", function() {
// Slicing 5 characters from the URL.
const url = location.href.slice(0, -5)
// Simply load the URL
location.href = url + "alt.html"
})
function updateView(category) {
console.log( window.location.hash );
if (location.hash !== ""){
//convert #3 to 3.
//load video based on id
//myArray[sanitizedHash];
} else {
updateCategoryLabel(category);
currentList = updateVideosList(category);
chooseRandomVideoFromList();
}
}
This function is loaded on page load
How can I parse inside this function so that the the location.hash's '#' will be taken out of the URL?
In short I am trying to achieve www.mysite.com/3 versus www.mysite.com/#3
Thanks in advance!
Edit: I should add that the 'else' is basically randomizing on page load versus going to the direct url. This if statement will run on page load to check if the hash exists otherwise it will randomize as usual.
Altering the URL from 'www.mysite.com/#3' to 'www.mysite.com/3' will cause the browser to navigate to a new URL since www.mysite.com/3 is not the same page as www.mysite.com/#whatever.
If you just want a string with the first character of the hash trimmed try:
window.location.hash.substr(1)
You can get the window.location.hash and then replace the # with an empty string
if (location.hash !== ""){
var sanitizedHash = window.location.hash.replace("#", "");
//load video based on id
//myArray[sanitizedHash];
}
If your goal is NOT to trigger page load, you can use HTML5 History API to change URL from www.mysite.com/#3 to www.mysite.com/3 like that:
var id = location.hash.substr(1);
history.replaceState({id:id}, id, id);
Note that replaceState is used, because otherwise user can press back button to the browser and get back to the #3. If you want to allow that, replace replaceState with pushState. Hope that helps.
I have a functional wordpress theme that loads content via ajax. One issue that I'm having though is that when pages are loaded directly the ajax script no longer works. For example the link structure works as follows, while on www.example.com and the about page link is clicked then the link becomes www.example.com/#/about. But when I directly load the standalone page www.example.com/about, the other links clicked from this page turn into www.example.com/about/#/otherlinks. I modified the code a little bit from this tutuorial http://www.deluxeblogtips.com/2010/05/how-to-ajaxify-wordpress-theme.html. Here is my code. Thanks for the help.
jQuery(document).ready(function($) {
var $mainContent = $("#container"),
siteUrl = "http://" + top.location.host.toString(),
url = '';
$(document).delegate("a[href^='"+siteUrl+"']:not([href*=/wp-admin/]):not([href*=/wp-login.php]):not([href$=/feed/]))", "click", function() {
location.hash = this.pathname;
return false;
});
$(window).bind('hashchange', function(){
url = window.location.hash.substring(1);
if (!url) {
return;
}
url = url + " #ajaxContent";
$mainContent.fadeOut(function() {
$mainContent.load(url,function(){
$mainContent.fadeIn();
});
});
});
$(window).trigger('hashchange');
});
The problem you are expressing is not easily solved. There are multiple factors at stake but it boils down to this :
Any changes to a URL will trigger a page reload
Only exception is if only the hash part of the URL changes
As you can tell there is no hash part in the URL www.example.com/about/. Consequently, this part cannot be changed by your script, or else it will trigger page reload.
Knowing about that fact, your script will only change the URL by adding a new hash part or modifying the existing one, while leaving alone the "pathname" part of the URL. And so you get URLs like www.example.com/about/#/otherlinks.
Now, from my point of view there are two ways to solve your problem.
First, there is an API that can modify the whole URL pathame without reload, but it's not available everywhere. Using this solution and falling back to classical page reload for older browser is the cleaner method.
Else, you can force the page reload just once to reset the URL to www.example.com/ and start off from a good basis. Here is the code to do so :
$(document).delegate("a[href^='"+siteUrl+"']:not([href*=/wp-admin/]):not([href*=/wp-login.php]):not([href$=/feed/]))", "click", function() {
location = location.assign('#' + this.pathname);
return false;
});
It should be noted that this script won't work if your site is not at the root of the pathname. So for it to work for www.example.com/mysite/, you will need changes in the regex.
Please let me know how it went.
I'm using jquery to rewrite a list of links on the page. If the location.host is NOT the vendor location.host AND the cookie isn't set to a specific value then it locates the links and rewrites them to the alternate values. The code I'm using works great in FF but not in IE7. Please help!
<script type="text/javascript">
// link hider
var hostadd = location.host;
var vendor = '172.29.132.34';
var localaccess = 'internal.na.internal.com';
var unlock = 'http://internal.na.internal.com/Learning/Customer_Care/navigation/newhire.html';
// link rewriter
$(document).ready (
function style_switcher(){
//if not a vendor or not accessing from lms reroute user to lms
if (hostadd != vendor && $.cookie("unlockCookie") != unlock){
var linkData = {
"https://www.somesite.com": "https://internalsite.com/something",'../Compliance/something/index.html':'../somethingelse.html'
};
$("a").each(function() {
var link = this.getAttribute("href"); // use getAttribute to get what was actualy in the page, perhaps not fully qualified
if (linkData[link]) {
this.href = linkData[link];
}
});
}
});
</script>
What you could do, if you insert the links dynamic, is store them in a data attribute like data-orglink="yourlink" which wouldnt be transformed by the browser, then check on that -and if its in the object array - change the href. Do you have access to creating the data attribute?
IE7 have problems with internal links, because it puts the host info on, before JS can reach the link..
http://jsfiddle.net/Cvj8C/9/
Will work in all, but IE7. So you need to use full paths if to use JS for this function :(
You had some errors in your JS.
But it seems to work fine?
See: http://jsfiddle.net/s4XmP/
or am i missing something? :)
As far as I know, if you want to load JavaScript or CSS files together with a specific page that is automatically loaded via ajax then you have to put the CSS/JavaScript references within the <div data-role="page"> container.
Example:
<div data-role="page" data-theme="e">
<script type="text/javascript" src="/js/jquery/plugins/plugins.js"></script>
In general, this works fine. However, somewhere along the way, the script url gets modified:
/js/some_sepcial_script.js becomes e.g. js/some_sepcial_script.js?_=1299308309681
Where 1299308309681 is the current Unix timestamp which changes on every request and thus prevents caching. I am pretty sure that this is intended behaviour but does anyone know how you can prevent the timestamp from being appended to the script/CSS urls if you want to make the file cacheable?
Have you tried:?
$.ajax ({
// Disable caching of AJAX response */
cache: false
});
It should globally change ajax requests. I'm just not sure about external scripts.
[EDIT]
This is the source code involved for jquery mobile 1.0a3:
var all = $("<div></div>");
//workaround to allow scripts to execute when included in page divs
all.get(0).innerHTML = html;
to = all.find('[data-role="page"], [data-role="dialog"]').first();
//rewrite src and href attrs to use a base url
if( !$.support.dynamicBaseTag ){
var newPath = path.get( fileUrl );
to.find('[src],link[href]').each(function(){
var thisAttr = $(this).is('[href]') ? 'href' : 'src',
thisUrl = $(this).attr(thisAttr);
//if full path exists and is same, chop it - helps IE out
thisUrl.replace( location.protocol + '//' + location.host + location.pathname, '' );
if( !/^(\w+:|#|\/)/.test(thisUrl) ){
$(this).attr(thisAttr, newPath + thisUrl);
}
});
}
Nothing on there adds a cache preventing param.
[EDIT 2]
I know this goes beyond troubleshooting to a work around but have you tried dynamically loading the js like explained here: http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml
(I know it can be done through jQuery but for testing purposes I'm trying to avoid jQuery)
if I include jQuery 1.4.3 instead of 1.5 everything works fine. That's a sufficient solution for me. Thanks again for your support.
Try running:
$.ajaxPrefilter("script", function (s) {
if (s.cache === undefined) {
s.cache = true;
}
});
Does it change this behavior?