Changing href value from JavaScript - 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";
}
});
});

Related

find and replace a unique html (href) string using javascript

Using Javascript, how can I change this classless anchor (assuming targeting unique href string):
to this, on page load:
You can select the element based on its href prop.
$('a[href="/unique-url-string/"]').prop('href', '/replacement-url-string/');
If you want to only search the pathname of these urls and keep the domain name the same you can try something like:
$('a').filter(function() {
return this.pathname === "/foo/bar"
}).prop('href', function () {
this.pathname = '/butt/butt/butt';
return this;
});
Using only JavaScript without library
function replaceLink(oldLink, newLink) {
var x = document.getElementsByTagName("a");
for(var i = 0; i < x.length; i++)
if(x[i].href == oldLink) {
x[i].href == newLink;
break;
}
}
}
Try this:
$(function(){
$('a[href="/unique-url-string/"]').attr('href', '/replacement-url-string/');
});
To replace a portion:
$(function(){
var a = $('a[href="/unique-url-string/"]');
a.attr('href', a.attr('href').replace('unique', 'replacement'));
});
var link = document.getElementById('linkToChange');
console.log(link.href);
link.href = "http://www.google.com";
me
Just do this :
$().ready(function(){
$('a').attr("href").replace("unique","replacement");
});

Check if href equals a certain value

Currently im looping through links in a page and checking if the link contains a string to determine the url. Heres my current code:
$( ".domain a" ).each( function () {
if ($(this).is(':contains("imgur")')) {
This can detect if the element contains the string "imgur", but because of this is a link goes to a site like slimgur.com, it will also return true.
How can I properly check that the url is, in this example, imgur.com or any of its subdomains (i.imgur.com & m.imgur.com) and that a url such as slimgur.com wont return true?
Rather than check the text, use the properties associated to an <a> tag like hostname.
$( ".domain a" ).filter(function(){
return this.hostname === 'imgur.com';
}).doSomething();
DEMO
This will do it:
$( ".domain a" ).each( function() {
var str = 'imgur';
if($(this)[0].hostname.split('.').indexOf(str) > -1) {
console.log('Found ' + str);
}
})
You could do something like: JS Fiddle
$('a').each(function () {
var url = "yahoo.com";
var anchor = $(this).attr('href');
var domain = url_domain(anchor);
if (url === domain) {
//Do something here
}
});
function url_domain(data) {
var a = document.createElement('a');
a.href = data;
return a.hostname;
}
url_domain() function found here: Extract hostname name from string

repeating jquery function many times

I need to improve my jquery code where I repeat my function 6 times!!!
is there away to do a loop to shorten the code ?
(function( jQuery ){
jQuery.fn.vesta = function(imgN){
var imgPath = "http://localhost:8080/mhost/media/magentohost/vesta/vesta"
var currImg = imgPath + imgN + ".png";
var targetImg = jQuery('.img-browser img');
jQuery('.img-browser img').attr('src', currImg);
}
})( jQuery );
jQuery('.vesta1').on('click', function (e) {
jQuery('.vesta1').vesta(1);
});
jQuery('.vesta2').on('click', function (e) {
jQuery('.vesta2').vesta(2);
});
jQuery('.vesta3').on('click', function (e) {
jQuery('.vesta3').vesta(3);
});
jQuery('.vesta4').on('click', function (e) {
jQuery('.vesta4').vesta(4);
});
jQuery('.vesta5').on('click', function (e) {
jQuery('.vesta5').vesta(5);
});
jQuery('.vesta6').on('click', function (e) {
jQuery('.vesta6').vesta(6);
});
You can DRY this up by using a common class, and a data attribute to specify the parameter to send to your vesta function:
<div class="vesta" data-vesta="1">1</div>
<div class="vesta" data-vesta="2">2</div>
<div class="vesta" data-vesta="3">2</div>
Then there is no need to loop at all:
$('.vesta').on('click', function (e) {
$(this).vesta($(this).data('vesta'));
});
Use a common class and a data attribute
jQuery('.vesta').on('click', function (e) {
var elem = $(this);
elem.vesta(elem.data("ind"));
});
and the HTML
<div class="vesta vesta1" data-ind="1">
Just put it into a for loop, and take advantage of the dynamic nature of JavaScript:
for (var i = 1; i <= 6; i++) {
$('.vesta' + i).on('click', (function (index) {
return function (e) {
$('.vesta' + index).vesta(index);
};
})(i));
}
I suppose you need the this reference along with some hack kind of thing
$('[class*=vespa]').on('click', function(e){
$(this).vesta(+(this.className.match(/vespa(\d+)/)[1]))
});
Here, we capture elements which have a class that matches at least vespa and then we use some bit of regex to match the digits after vespa and + unary operator changes the String version of numbers into actual numbers.
It would be quite easy if you can alter the structure of the HTML.
You would give all elements the same class, say vesta. But you also give them an attribute, say data-number. For example, like this:
<div class="vesta" data-number="4"></div>
Then, your jQuery code would be as simple as:
$(document).on({
click: function() {
var $this = $(this),
number = +$this.data('number');
$this.vesta(number);
}
}, '.vesta');
Edit:
I was a bit lazy with explaining the code snippet that I have provided an hour ago, but I am modifying my post now in response to the comments.
This code snippet will allow you to apply listeners from '.vesta1' elements to '.vestaN'
[#Variable]
NumberOfClasses - is the positive integer after 'vesta'. Eg: vesta1 ,vesta2, vesta100 ... etc
var NumberOfClasses=6;
for(var i=1;i<=NumberOfClasses;i++){
var className = '.vesta'+(i+1);
jQuery(className ).on('click', function (e) {
$(this).vesta(i);
});
}

field value gets undefined jquery

Can I Clear a event que in javascript?
when I have done one click event and then does another click event the input field gets the value undefined even when it has a value like "newfile.jpg"
I retrieves the values by doing somevariable = $('#cke_104_textInput').val();
but somevariable gets the value undefined.
here is the javascript code:
$(function () {
// Handler for .ready() called.
function changeLink() {
link = $('#cke_104_textInput').val();
if (link == "") {}
else {
link = link.replace("_", "/");
parts = link.split('.');
explodeExtension = parts[parts.length - 1];
link = link.replace("/download/", "/download/" + explodeExtension + "/");
link = link.replace("." + explodeExtension, "");
$('#cke_104_textInput').val('');
$('#cke_104_textInput').val(link);
clearInterval(changelink);
}
}
function changePic() {
link = $('#cke_103_textInput').val();
if (link == "") {}
else {
link = link.replace("_", "/");
parts = link.split('.');
explodeExtension = parts[parts.length - 1];
link = link.replace("/download/", "/show/" + explodeExtension + "/");
link = link.replace("." + explodeExtension, "");
$('#cke_103_textInput').val('');
$('#cke_103_textInput').val(link);
clearInterval(changepic);
}
}
$('#cke_60').live('click', function (event) {
changelink = setInterval(function () {
changeLink()
}, 1000);
});
$('#cke_64').live('click', function (event) {
changepic = setInterval(function () {
changePic()
}, 1000);
});
});
In the code i try to rewrite the content of two input fields.
this has to be done because the files are not in the sites root they are outside of it, and to be able to show or download them on the site the urls need to be in a specific format.
To answer your first line question, yes you can. Take a look at unbind()
You are creating link as a global variable, which means it is clashing with itself.
Change link = $('#cke_104_textInput').val(); to var link = $('#cke_104_textInput').val();.
Also as a side note, you have this code twice:
$('#cke_104_textInput').val('');
$('#cke_104_textInput').val(link);
which is redundant and inefficient. You should remove the first line in both cases, because selecting an element (even via ID) is not a free operation.

Detecting Href Is Clicked

I'm trying to detect if certain element is clicked on onbeforeunload. I can't get it to work. Below is examples of the Javascript code and HTML code on the project (Please note that I have no control over the HTML element as it is not my site)
function checkLeave() {
var p = document.getElementByElementById('yeah');
if (p.href.onclick) {
//do something
}
else {
//do something else
}
}
window.onbeforeunload = checkLeave;
HTML CODE
//The goSomewhere goes to another page
<a id="yeah" href="javascript:goSomewhere();">
<img src="smiley.png">
</a>
Thanks in advance,
J
What you need to do is bind an event handler to each on the page.
This can be done with the following:
// Select all links
//var allLinks = document.querySelectorAll('a[href]');
var allLinks = document.links;
// Bind the event handler to each link individually
for (var i = 0, n = allLinks.length; i < n; i++) {
//allLinks[i].addEventListener('click', function (event) {});
allLinks[i].onclick = function () {
// Do something
};
}
You are testing for the presence of the onclick property to the <a> tag. It isn't present in the markup. Rather than using the onclick, the markup calls a script as the element's href. So you need to look for a script in the href instead:
var p = document.getElementByElementById('yeah');
if (p.href.indexOf("javascript") === 0) {
//do something
}
else {
// do something else
}
Maybe something like this? (just the idea)
document.getElementById('yeah').onclick = function() {
clicked = this.href;
};

Categories

Resources