I have following function:
It bassicly takes the value form clicked href and than load file into the #loader div with the same name.
$('.loader').click( function() {
// Check clicked element href
var ActiveTab = $(this).attr("href");
//Content
var TrimedClickedTab = $(this).attr("href").substring(1);
$('#loaderDiv').load( TrimedClickedTab +'.html', function() {
// Show New Loaded Div
});
return false;
});
How can I pass param into the function form the URL and than run it with this param?
I want the URL to set the var ActiveTab = "#form"
I'm looking to run this on the load, so it would load straight away given file. ( var #ActiveTab)
I think you're looking for something like this:
var path = document.location.toString();
var anchor = '#' + path.split('#')[1];
So, if your URL looks like "http://example.org/test#form", anchor will contain "#form"
Related
I currently have the following:
$( "#Coupon" ).keyup(function() {
$(this).val (function () {
return this.value.toUpperCase();
})
var url = window.location.href;
var addon = $('#voucher').val();
$("#ApplyCoupon").attr('href', url + "&coupon=" + addon);
which checks a text field and then adds the content to a url variable to check if the coupon is vali the next time the page loads.
My issue is that if you check multiple coupons, it keeps adding &coupon=blah
Is there any way of just replacing the coupon variable in the URL instead of creating new ones?
I want to toggle between two jQuery functions. It has to be done on page load - and each page load should only execute one of the scripts.
This is what I got so far:
HTML:
<button class=".click">Click me</button>
Script:
$(function() {
if (window.location.href.indexOf("addClass") > -1) {
$("body").addClass("test");
}
else {
$("body").addClass("secondtest");
}
$('.click').on('click', function() {
console.log("Clicked");
var url = window.location.href;
if (url.indexOf('?') > -1) {
url += '?param=addClass'
} else {
url += '?param=1'
}
window.location.href = url;
});
});
This Gets me a bit on the way, the first click adds ?param=1 on the first click - nothing happens - second click it adds the ?param=addClass and the body gets the class. If I click again it adds ?param=addClass every time.
I want one of the script to run as default - then I want the first button click to reload and run the other script instead. If I click once more I want it to reverse the url so the first script loads, like a toggle.
I now there is an easy way to just toggle classes, but I specifically need to run one of two scripts on a new page load.
Update:
$(function() {
if (window.location.href.indexOf("addClass") > -1) {
$("body").addClass("test");
}
else {
$("body").addClass("secondtest");
}
$('.click').on('click', function() {
console.log("Clicked");
var url = window.location.pathname;
var url = window.location.href;
if (url.indexOf('?param=1') > -1) {
url = url.replace("param=1", "")+'param=addClass'
} else {
url = url.replace("?param=addClass", "")+'?param=1'
}
window.location.href = url;
});
});
This set the body class on first page load - then first click ads ?param=1 but doesnt change the body class. Second click replaces ?param=1 with ?param=addClass and changes the body class - after that the toggles works. So How do I make it work from the first click?
This will be the default functionality, if no query string is present then add ?param=1:
var url = window.location.href;
if(url.indexOf('?param=1')==-1 )
{
window.location.href = url+"?param=1";
}
This will be the onclick functionality to toggle the urls as it is replacing the existing functionality.
$('.click').on('click', function() {
var url = window.location.href;
if (url.indexOf('?param=1') > -1) {
url = url.replace("param=1", "")+'param=addClass'
} else {
url = url.replace("?param=addClass", "")+'?param=1'
}
window.location.href = url;
});
If you want to toggle the classes as well you can use .toggleClass("test secondtest")
The issue you have is in this if:
var url = window.location.href;
if (url.indexOf('?') > -1) {
url += '?param=addClass'
} else {
url += '?param=1'
}
Scenario 1: /test.html
indexOf('?') will be negative. You will then redirect the user to /test.html?param=1
Scenario 2: /test.html?param=1
indexOf('?') will then be positive. You will then redirect the user to /test.html?param=1?param=addClass
Scenario 3: /test.html?param=addClass
indexOf('?') will then be positive. You will then redirect the user to /test.html?param=addClass?param=addClass
So... what is wrong?
You are using window.location.href. Excellent for setting the path but bad if you want to actually manage the query parameters.
Solution
var url = window.location.pathname;
var hasParams = window.location.href.indexOf('?') > -1;
if (hasParams) {
url += '?param=addClass'
} else {
url += '?param=1'
}
window.location.href = url;
Since you are redirecting on the same host (seen with your code), you only need the pathname. pathname doesn't include parameters (?key=value&...) and can be used to redirect a user on the same domain.
This code gives each Colorbox image an URL (domain.com/#image). This can then be copied and pasted by user to open the wanted photo automatically when entering the site with that URL.
Everything works as intended but somehow it also auto-opens the first image on the site even when there is no #image at the end of the URL. How should I change this code that it will only auto-open the image when there is #image in the URL?
Thanks!
Code:
jQuery(function (){
var id, group;
group = jQuery("a[rel='lightbox[63]']").colorbox({onComplete:function(){
// Get the image URL
with_ext = (this.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1];
// Get the image url without the extension
without_ext = with_ext.substring(0, with_ext.lastIndexOf("."));
// Redirect
window.location.hash = without_ext;
}, onClosed: function(){
location.hash = '';
}});
id = location.hash.replace(/^\#/, '')+".jpg";
group.filter('[href$="'+id+'"]').eq(0).click();
});
Ok got it working.
If anyone else needs this kind of function here it is:
jQuery(function (){
var id, group;
group = jQuery("a[rel='lightbox[63]']").colorbox({onComplete:function(){
// Get the image URL
with_ext = (this.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1];
// Get the image url without the extension
without_ext = with_ext.substring(0, with_ext.lastIndexOf("."));
// Redirect
window.location.hash = without_ext;
}, onClosed: function(){
location.hash = '';
}});
if(window.location.hash) {
id = location.hash.replace(/^\#/, '')+".jpg";
group.filter('[href$="'+id+'"]').eq(0).click();
} else {
return;
}
});
I have the following code in MVC3 view:
$(document).ready(function () {
if (window.location.hash) {
var manager= new Manager();
manager.doSomeStuff(window.location.hash);
}
});
The interesting thing is that when there is no hash tag in the URL, or there is only a hash tag example:
http://localhost:1223/Index/AboutUs
http://localhost:1223/Index/AboutUs#
When the window.location.hash is empty and the function is not executed.
But when there is some value in the hash tag:
http://localhost:1223/Index/AboutUs#categoryId=5&manufacturerId=8
The value in the window.location.hash is #categoryId=5&manufacturerId=8
Can you explain to me why the # tag is included in the value and why when there is no value after the # tag, the window.location.hash is empty.
There's nothing much to explain. It is the way it works.
Read more here: http://www.w3schools.com/jsref/prop_loc_hash.asp
Definition and Usage
The hash property returns the anchor portion of a URL, including the hash sign (#).
You can change it if you want by simply changing the hash name:
//Your old hash name caught in a variable
var nameHash = location.hash;
//Your new hash name without "#"
var newHashName = nameHash.replace("#","");
var hash = window.location.hash.substring(1);
This omits the first character of the string, which is the hash tag.
You can repalce # but this way will create conflict and won't work with javascript.
Here is window.location reference link.
Here is different usage examples:
$(document).ready(function () {
var urlHash = window.location.hash;
var sampleURL = '#categoryId=5&manufacturerId=8';
if ( urlHash.length > 1 ) {
//do stuff
}else{
//if value is empty, do stuff
}
if ( urlHash === sampleURL ) {
commonResponse();
}
$('a').click(function() {
var target = $(this).attr('href');
if (target === sampleURL ) {
commonResponse();
}
});
function commonResponse() {
//alert('ok');
}
});
Is there a simple way to get the parameters at the end of an href attribute of a clicked link using the click event object?
I have some jQuery code that looks like this:
$(document).ready(function() {
$('#pages').delegate("a", "click", function(e) {
var formData = "parameters to clicked link";
$.ajax({
url: 'friends2.php',
dataType: 'json',
data: formData,
success: function(data) {
$('#searchbutton').attr("disabled", false);
$('#searchresults').html(data.results);
$('#pages').html(data.paginate);
}
});//ajax end
return false;
});
});
And here is the relevant HTML:
<div id="pages">
<span class="disabled">previous</span>
<span class="current">1</span>
2
</div>
What I'm trying to do is paginate the results of a search that I've done with ajax. The search runs fine and a get a list of users that match the query. The part of the results script that creates the pagination links is also working.
In the example above, there are two pages of results. What I want to do when a user clicks the link to go to page 2 of the results is to intercept the link click and instead create a new ajax request using term=ma&p=2 as the data passed to the request.
So, long story short, is there an easy way to get term=ma&p=2 from the event object passed the the anonymous function in my jQuery above?
You can use the this.href method to read the link attribute:
$('#pages').delegate("a", "click", function(e) {
var str = this.href.split('?')[1];
Example:
str = 'friends.php?term=ma&p=2';
console.log(str.split('?')[1]); // output: term=ma&p=2
Yes, you can use the .search property of the link...
alert( this.search );
DEMO: http://jsfiddle.net/sHqmF/
To get rid of the ?, just .slice() it...
this.search.slice(1)
DEMO: http://jsfiddle.net/sHqmF/1/
Developing Sarfraz answer, given an anchor
<a class="the_link" href="http://www.example.com/?a=1&date=2014-7-30&cat=all">click here</a>
You can get the query params
jQuery(document).ready(function($) {
$('a.the_link').click(function(){ // when clicking on the link
var href = $(this).attr('href'); // get the href of the anchor
var params = get_params_from_href(href);
console.log(params); // OUTPUT: [a: "1", date: "2014-7-30", cat: "all"]
return false; // optional. do not navigate to href.
});
function get_params_from_href(href){
var paramstr = href.split('?')[1]; // get what's after '?' in the href
var paramsarr = paramstr.split('&'); // get all key-value items
var params = Array();
for (var i = 0; i < paramsarr.length; i++) {
var tmparr = paramsarr[i].split('='); // split key from value
params[tmparr[0]] = tmparr[1]; // sort them in a arr[key] = value way
}
return params;
}
}
jQuery itself doesn't support URL parsing. However there are lots of jQuery extensions available which do and make this an easy task. For example
https://github.com/allmarkedup/jQuery-URL-Parser
With this extension you can do the following
$('#pages').delegate("a", "click", function(e) {
var href = $(this).attr('href');
var url = $.url(href);
var query = url.attr('query')
...
});
The extension itself supports much more than just the query string. You can use attr for practically every part of the url.