Adding variable at the end of URL using jQuery - javascript

So far I have done
jQuery:
function addURL(element)
{
var baseZipCode = 48180;
$(element).attr('href', function() {
return this.href + baseZipCode;
});
}
html:
<a onclick="addURL(this)" href="http://www.weather.com/weather/today/" target="_blank">Click this</a>
My problem is when user clicks on link and the new window open everything is ok, but when the user clicks on the link again without a refresh, the variable is added twice to the link.
For example:
First time:
http://www.weather.com/weather/today/48180
Second time:
http://www.weather.com/weather/today/4818048180
It doesn't act right until you do a page refresh, any help would be appreciated. Thanks in advance

Replace your addURL function with
function addURL(element)
{
var baseZipCode = '48180';
if (element.href.slice(-baseZipCode.length) !== baseZipCode){
element.href += baseZipCode;
}
}
there is no jQuery involved..

You can try it with jQuery.fn.one
Javascript:
jQuery("a").one("click", function(){ // Set a handler that execute once
var baseZipCode = 48180;
this.href += baseZipCode; //same as "this.href = this.href + baseZipCode"
});
HTML:
Click this
Maybe you will need to add some class to <a> tags to differ it from another ones

This should be:
function addURL(element)
{
var baseZipCode = 48180;
element.href = (element.href + baseZipCode)
.replace(baseZipCode + baseZipCode, baseZipCode);
}

return this.href.indexOf(baseZipCode) != -1 ? this.href : this.href + baseZipCode;

Related

Changing href value from JavaScript

I have this example in JsFiddle.
http://jsfiddle.net/PtNfD/114/
Yahoo
Not working
$(document).ready (function () {
$('#changeMe'). click (function (e) {
var goLucky = Math.floor(Math.random()*12);
if (goLucky % 2 == 0) {
this.href = "http://www.google.com";
} else {
this.href = "http://www.hotmail.com";
}
});
});
The href change works in the first link, but not in the second. How can I make it work for both links??
The number of links in my page is dynamic, because I create the links with PHP, so I need the href change to work in all generated links.
id attributes must be unique. You should convert the value changeMe to a classname for use on multiple elements. Then your existing code should work:
Yahoo
Not working
$(document).ready (function () {
$('.changeMe'). click (function (e) {
var goLucky = Math.floor(Math.random()*12);
if (goLucky % 2 == 0) {
this.href = "http://www.google.com";
} else {
this.href = "http://www.hotmail.com";
}
});
});
Optionally, you could add a unique id to the second anchor tag and modify the JavaScript code accordingly.
You cannot use an ID on two different elements in HTML. You need to asign each of those a different ID or the same class instead and then apply your href change on each of the IDs, or the class
IDs should be used once per webpage. Classes can be used more plentifully. Remember your specificity. Use class instead of id: http://jsfiddle.net/PtNfD/115/
Yahoo
Not working
$(document).ready (function () {
$('.changeMe'). click (function (e) {
var goLucky = Math.floor(Math.random()*12);
if (goLucky % 2 == 0) {
this.href = "http://www.google.com";
} else {
this.href = "http://www.hotmail.com";
}
});
});

JS popup does't works comparison operator

I have 5 link and mini preview photo and url 3 links its good link opsss and upsss is wrong when i click good link i'm going to new page when i click error link attr href change to adresError and then we have popup This only works for the first time second time click all links have a popup and should have only opsss and upsss
http://jsfiddle.net/3ptktp47/1/
Here is my code :
var nameError = [
"opsss",
"upsss",
];
$(function() {
$('#prev').hide();
$(function() {
var title_link = 'kliknij aby podejżeć';
$(".preview-link a")
.attr({title: title_link})
//.tooltip()
.click(function(){
$('.preview-link a img').css('opacity',1);
var sciezka = $(this).attr("href");
var tytul = $(this).attr("title");
var adres = $(this).text();
//alert(adres);
$(".duzy").attr({ src: sciezka, alt: tytul, style:'cursor:pointer;', href:'http://www.'+ adres,'target':'_blank'});
$('.link').html(adres).attr({href:'http://www.'+ adres,'target':'_blank'});
$('#prev').show();
function errorDomain() {
$('.link, .duzy').removeAttr('href');
$('.link, .duzy').click(function(event){
$('#popup, .popup-bg').show('slow');
$('.server_url').html(adresError).attr({href:'http://'+ adresError,'target':'_blank'});
});
};
if(adres == 'opsss.com'){
var adresError = 'x4ql.nazwa.pl/'+ nameError[0];
errorDomain();
}else if(adres == 'upsss.com' ){
var adresError = 'x4ql.nazwa.pl/'+ nameError[1];
errorDomain();
}else{
//$('#popup, .popup-bg').fadeOut();
};
$('.cancel, .popup-bg').click(function(event){
$('#popup, .popup-bg').fadeOut();
});
return false;
});
$('.close').click(function(){
$('#prev').hide();
});
$('.link').mouseover(function(){
$(this).css({style: 'color:#000;'});
});
});
});
EDITED:
Ok, I was able to handle your problem.
Your .click() event in the errorDomain() method was firing every time you clicked this square. I managed it to toggle a class on a.duzy element with toggleClass('error') in your if-statement where you check the address.
Inside your click() event, a if-statement is checking if the .duzy element has class named error with hasClass('error') , this has following result -
TRUE- your popup will be displayed
FALSE - nothing happens
I hope my answer is clear enough, but please check out the edited fiddle.
EDITED SOURCE:
Your errorDomain() Method
function errorDomain() {
$('.link, .duzy').removeAttr('href');
$('.duzy, .link').click(function (event) {
if ($(this).hasClass("error")) {
$('#popup, .popup-bg').show('slow');
$('.server_url').html(adresError).attr({
href: 'http://' + adresError,
'target': '_blank'
});
}
});
}
The if-statements
if (adres == 'opsss.com') {
var adresError = 'x4ql.nazwa.pl/' + nameError[0];
$('a.duzy').toggleClass("error");
errorDomain();
} else if (adres == 'upsss.com') {
var adresError = 'x4ql.nazwa.pl/' + nameError[1];
$('a.duzy').toggleClass("error");
errorDomain();
} else {
$('a.duzy').removeClass("error");
}
Edited fiddle

How to link to tabs with jtabs?

I added tabs to a section of my page I am working on (stridertechnologies.com/stoutwebsite/products.php)using the steps found at this website: http://code-tricks.com/create-a-simple-html5-tabs-using-jquery/
I want to link to the different tabs from the home page, but I am not sure how to do that outside of anchor names with html and that doesn't work with this, and there aren't any instructions on how to do it on the site.
It seems like there should be something really simple I can add to my javascript to detect which link they clicked on and make it the active tab.
javascript:
;(function($){
$.fn.html5jTabs = function(options){
return this.each(function(index, value){
var obj = $(this),
objFirst = obj.eq(index),
objNotFirst = obj.not(objFirst);
$("#" + objNotFirst.attr("data-toggle")).hide();
$(this).eq(index).addClass("active");
obj.click(function(evt){
toggler = "#" + obj.attr("data-toggle");
togglerRest = $(toggler).parent().find("div");
togglerRest.hide().removeClass("active");
$(toggler).show().addClass("active");
//toggle Active Class on tab buttons
$(this).parent("div").find("a").removeClass("active");
$(this).addClass("active");
return false; //Stop event Bubbling and PreventDefault
});
});
};
}(jQuery));
This answer is from a duplicated question here: https://stackoverflow.com/a/20811416/3123649.
You could pass the tab div id in the url from the link and use that to select.
Home page links from index.html:
tile
metal
Add this javascript to the tab page
<script type="text/javascript">
// To get parameter from url
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
$.extend($.expr[':'], {
attrNameStart: function (el, i, props) {
var hasAttribute = false;
$.each(el.attributes, function (i, attr) {
if (attr.name.indexOf(props[3]) !== -1) {
hasAttribute = true;
return false;
}
});
return hasAttribute;
}
});
// deselect tabs and select the tab by id
function focusTab(id) {
$("#tile").hide().removeClass("active");
$("#metal").hide().removeClass("active");
$("#shingle").hide().removeClass("active");
$("#flat").hide().removeClass("active");
$("#custom").hide().removeClass("active");
var toggle = $(id).parent().find("div");
toggle.hide().removeClass("active");
$('a:attrNameStart(data-toggle)').removeClass("active");
var id1 = getParameterByName("tabId");
var toggler = $('*[data-toggle=' + id1 + ']');
$(toggler).addClass("active");
$(id).show().addClass("active");
}
$(function() {
$(".tabs a").html5jTabs();
// Get the tab id from the url
var tabId = "#" + getParameterByName("tabId");
// Focus the tab
focusTab(tabId);
});
</script>
EDIT: Replace the original focusTab function with the edit. Also add the extend function attrNameStart. This should deselect the default active tab.
EDIT2: focusTab had a bug, it should work now
** I looked at your site and my solutions seems to be working for you. One thing I noticed. You initialize the html5jTabs() twice.
Remove the first call at the top
<script type="text/javascript">
$(function() {
$(".tabs a").html5jTabs();
});
</script>
How about something like this? Basically we are taking the value of data-toggle in our buttons, and passing it into the selector for each tab content
JS
$('a[data-toggle]').on('click', function () {
var dataToggle = $(this).data('toggle');
$('.tabContent > div').removeClass('active');
$('.tabContent > div#'+dataToggle+'').addClass('active');
});
working example:
http://jsfiddle.net/whiteb0x/VdeqY/

How to dynamically change the anchor tag link?

I'm trying to remove a landing page when I click on a link on a page. The page isn't mine so I'm trying to change the href with a user script.
Without any modification, the link looks like this:
https://www.domain.com/out.php?u=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DPUZ1bC-1XjA%26amp%3Bfeature%3Drelated
What I want:
http://www.youtube.com/watch?v=PUZ1bC-1XjA&feature=related
What I got so far:
http://www.youtube.com%2fwatch%3fv%3dpuz1bc-1xja%26amp%3bfeature%3drelated/
But that adress doesn't work in the browser.
This is my current code:
$('a').each(function(index) {
var aLink = $(this).attr('href');
if(aLink) {
if(aLink.indexOf("out.php?u=") > 0) {
aLink = aLink.substring(51);
console.log(aLink);
$(this).attr('href', "http://"+aLink);
console.log($(this).prop('href'));
}
}
});
All help and tips are appreciated.
You need to decode the URL using decodeURIComponent
Change:
$(this).attr('href', "http://"+aLink);
To:
$(this).attr('href', 'http://' + decodeURIComponent(aLink));
Take a look at decodeURIComponent
You can also make use of the hostname, pathname, and search parameters of anchor elements.
// general function to turn query strings into objects
function deserialize_query_string(qs) {
var params = {};
var fields = qs.split('&');
var field;
for (var i=0; i<fields.length; i++) {
field = fields[i].split('=');
field[0] = decodeURIComponent(field[0]);
field[1] = decodeURIComponent(field[1]);
params[field[0]] = field[1];
}
return params;
}
$(document.links).each(function(i){
if (this.hostname=='www.domain.com' && this.pathname=='/out.php') {
var params = deserialize_query_string(this.search);
if (params.u) {
this.href = u;
}
}
});

Reload all images on page

I'm trying to get all the images in the page to reload including backgound-image: rules
I have some semi working code but I want to know if there is an easier way of doing this.
function cacheBuster(url) {
return url.replace(/\?cacheBuster=\d*/, "") + "?cacheBuster=" + new Date().getTime().toString();
}
$("img").each(function() {
this.src = cacheBuster(this.src);
});
$("*").each(function() {
var bg_img = $(this).css("background-image");
if (bg_img !== "none") {
var url = /url\((.*)\)/i.exec(bg_img);
if (url) {
$(this).css("background-image", "url(" + cacheBuster(url[1]) + ")");
}
}
});
Looks fine but you are missing inputs with type=image, that is images that act as a submit button. You can include them by adding following code
$("img, input[type=image]").each(function() {
this.src = cacheBuster(this.src);
});
Also you can change the code where you loop through all elements, just to include visible ones, if it is acceptable in your case.
$("*:visible")
Hope this helps.

Categories

Resources