Replacing href attribute with data-href attribute using Javascript - javascript

How can I do that for every 'a' tag in a page. My goal is to use this for Google search results to access results without google redirection (used in the href attribute) since the actual link is stored in the data-href attribute. So using Tampermonkey with the following script didn't work, and I don'k know why:
$('body').append('<input type="button" value="Fix Href Attributes" id="GG">');
$("#GG").css("position", "fixed").css("top", 18).css("left", 770);
$('a').each(function(){
var $currentA = $(this);
var dataHref = $currentA.attr('data-href');
$currentA.attr('href',dataHref);
});
How can I do this?

Your code updating the elements is correct, you're just firing it too soon. Fire it in response to the button being clicked:
$('body').append('<input type="button" value="Fix Href Attributes" id="GG">');
$("#GG").css("position", "fixed").css("top", 18).css("left", 770).on("click", function() {
$('a').each(function() {
var $currentA = $(this);
var dataHref = $currentA.attr('data-href');
$currentA.attr('href', dataHref);
});
});
There is, of course, no reason you need to give it an ID and look it up after appending it:
$('<input type="button" value="Fix Href Attributes">')
.css({
position: "fixed",
top: 18,
left: 770
})
.on("click", function() {
$('a').each(function() {
var $currentA = $(this);
var dataHref = $currentA.attr('data-href');
$currentA.attr('href', dataHref);
});
})
.appendTo(document.body);

Related

jQuery doesn't let me use href

jquery:
$(".container").on("click", function(e) {
e.preventDefault();
var currentBox = $(this).siblings(".map").toggleClass("active");
$(".map.active").not(currentBox).removeClass("active");
});
html:
Because of this i cant use href anymore.
I use the jqueryto show more links.
It appears that you're trying to use div's and p's like anchors (a). href is not a valid attribute of div or p.
If you're trying to store data in the div and p tags, use data-href="" in conjunction with window.open()
Based on the limited code provided, my guess is that you're trying to do something like this:
$(".container").on("click", function(e) {
e.preventDefault();
const $this = $(this);
$(".map.active").removeClass("active");
$this.siblings(".map").toggleClass("active");
let href = $this.attr("data-href");
// Open a new window
window.open(href);
// OR
// Navigate without opening new window
window.location.href = href;
});
Or, you could skip the jQuery all together an just use anchor tags as they're designed to be used.
You can use jQuery for get any attribute of elements. So if you want to use href, just do:
var new_location = $('a').attr('href');
So you can do anything by click on a tag and at the least redirect to href path by:
window.location.href = $(this).attr('href');
Note: $(this) point to current clicked a tag. So you have something like this:
$(".container").on("click", function(e) {
e.preventDefault();
var currentBox = $(this).siblings(".map").toggleClass("active");
$(".map.active").not(currentBox).removeClass("active");
window.location.href = $(this).attr('href');
});

Transforming href links on pageload using jquery

I need to transform all the links(href values) to specific format
for example - if a page has a link http://www.exampledomain.com i want to convert its href to http://url.com/xyz?http://www.example.com
Below is the jquery i am using for this task (Note that i am new to jquery)
$( document ).ready(function() {
$('a').each(function() {
var value = $(this).attr('href');
$(this).attr('href','http://url.com/xyz?'+value);
});
});
But above script is converting all the links of the website and my navigational links are also getting changed. How can we filter to change only the href's of links that contain 'http' and 'www'?
I know some kind of regex can be used for this purpose. Thanks in advance!
I thinks you should extract all internal links.
You can check if value match your criteria (http://www):
$( document ).ready(function() {
$('a').each(function() {
var value = $(this).attr('href');
if(value.indexOf("http:\\www") > -1 ){
$(this).attr('href','http://url.com/xyz?'+value);
}
});
But it will be better to extract all the internal links:
var myHost = new RegExp(location.host);
$('a').each(function(){
var value = $(this).attr('href');
if(!(myHost.test(value))){
$(this).attr('href','http://url.com/xyz?'+value);
}
});
The last and better option is to take just the external links: ( if you don't have to do anything to the internal)
$( document ).ready(function() {
$("a[href^='http']").each(function() {
var value = $(this).attr('href');
$(this).attr('href','http://url.com/xyz?'+value);
}
});
You could try for the following code
$( document ).ready(function() {
$('a').each(function() {
var value = $(this).attr('href');
if(value.match("http://www.*"))
{
$(this).attr('href','http://url.com/xyz?'+value);
}
});
});
You have to make sure that no navigation link contain
"http://www"
in them. Use relative links where you dont want to replace the href.
Or you could give a class to all anchor tags which you want to modify accordingly
Demo Fiddle
Check the anchor tag's href using element inspector
$('a').each(function() {
var a = new RegExp('/' + window.location.host + '/');
if(!a.test(this.href)) {
var value = $(this).attr('href');
$(this).attr('href','http://url.com/xyz?'+value);
}
});
using window.location.host and test
Modified from this article at CSS-Tricks.com
One approach:
// selects all 'a' elements:
$('a')
// sets the 'href' attribute, using the anonymous function to iterate over each
// 'a' element:
.attr('href', function(i,oldhref){
// i: the index of the current element in the returned collection,
// oldhref: the value of the 'href' before manipulation by the function.
// if 'exampledomain.com' features in the hostname of the link we
// manipulate the 'href' as required, otherwise we simply set the 'href'
// to its original value:
return this.hostname.indexOf('exampledomain.com') > -1 ? 'www.url.com/xyz?' + oldhref : oldhref;
});
JS Fiddle demo.
References:
JavaScript:
String.prototype.indexOf().
jQuery:
attr().
You can check the link is external or internal then you can add the additional effort.
$( document ).ready(function() {
$('a').each(function() {
var value = $(this).attr('href');
if($(this[href^='http'])
{
$(this).attr('href','http://url.com/xyz?'+value);
}
});
});

Append to a.href id from input field

I am trying to append to a link with id a value that is entered from the input text field. I came this far searching stackoverflow but id doesn't work!
<script type="text/javascript">
jQuery(function(){
$("#txt_name").keypress(function() {
var value = $("#txt_name").val();
});
$("a#coupon_link").attr("href", function(i) {
return href + '&discount_code='.text(value);
});
});
</script>
and this is how the html looks like
<form>
<fieldset>
<input id="txt_name" type="text" value="discount" />
</fieldset>
</form>
<a id="coupon_link" href="https://www.e-junkie.com/ecom/gb.php?c=cart&i=XXXXXX&cl=YYYYYY&ejc=2" target="ej_ejc" class="ec_ejc_thkbx" onClick="javascript:return EJEJC_lc(this);"><img src="http://www.e-junkie.com/ej/ej_add_to_cart.gif" border="0" alt="Add to Cart"/></a>
You probably meant this:
$(function() {
$("#coupon_link").on('click', function(e) {
e.preventDefault(); // apparently not needed
location.href = $(this).attr('href') + '&discount_code=' + encodeURIComponent($('#txt_name').val());
});
});
You don't have to update the value of #txt_name on keypress; you only have to use the value when the link is pressed.
Fix your code like this :
$(function(){
$("#txt_name").keypress(function() {
var value = $("#txt_name").val();
var link = $("#coupon_link");
var originalHref = link.attr('originalHref');
if (!originalHref) {
originalHref = link.attr("href");
link.attr("originalHref", originalHref)
}
link.attr("href", originalHref + '&discount_code='+value);
});
});
A few things to note :
never add anything to a selector when you're targeting an element by ID
your value variable wasn't in the same scope
the return of val can be directly concatenated, you don't need to try to change it to text
you don't need to pass a function to attr in your case
you're trying to make the href grow with every key stroke. This is a bad idea. The solution I propose is to keep the original href
if you're not sure the original href has yet some parameters (i.e. has '?') you should test it (I let you do that)
Overall a much cleaner solution wouldn't be to change the link but to build the href on click on the link :
$("#coupon_link").click(function(e) {
location = this.href + '&discount_code=' + $('#txt_name').val();
});
Not sure to understand, but it looks like a scope issue try this javascript :
<script type="text/javascript">
jQuery(function(){
var value = 0;
$("#txt_name").keypress(function() {
value = $("#txt_name").val();
$("a#coupon_link").attr("href", function(i) {
return href + '&discount_code=' + encodeURIComponent(value);
});
});
});
</script>
Try this:
jQuery(function(){
$("#txt_name").keypress(function() {
var value = $("#txt_name").val();
$("a#coupon_link").attr("href", '&discount_code=' + String(value));
});
});
This isnt working because the href isnt being changed as the function is called before a keypress event is triggered. Look into replacing keypress with blur and update the href when blur() is called
i think you need this:
<script type="text/javascript">
$(function(){
$("#txt_name").keypress(function() {
var value = $("#txt_name").val();
$("a#coupon_link").attr("href",href+'&discount_code='+value.toString);
});
});
</script>
look at href don't know where you have that var, if it is needed ok else remove that
You probably need to change the href when a key has been pressed, not only on page load. To do so you will have to do the replacing of the href inside the keyup function, like so:
$(function(){
var link = $("a#coupon_link");
link.data('href', link.attr("href"));
$("#txt_name").on('keyup', function() {
link.attr("href", link.data('href') + '&discount_code='+ this.value);
});
});
So as to not append the &discount_code=*** several times, you need to store the original href somewhere, like in a data attribute.
this one worked for me getting value from input field and append it to the existing link using jquery.
$('#qty').on('keyup', function() {
var theQty = 0;
theQty = $("#qty").val();
var oldHref=$("a#buybtn").attr("href");
$("a#buybtn").attr("href",oldHref+ '&qty=' + String(theQty));
});

Jquery syntax and variables

I'm trying to make a FadeOut effect after clicking a link. But my syntax seems to be wrong. When i click, it fadeout, and go to a "~~nothing~~.html" page, it just dont get the value to compose the variable.
the id boo is attached to the tag (body id="boo") and in the css stylesheet the id #boo is set to display:none;
I'm using jquery-1.7.2.min
<script type="text/javascript">
$(document).ready(function(){
$('#go').click(function(e) { //When something with the id 'go' is clicked,
e.preventDefault(); //Prevent default action (?)
var url = $('#go').val() + ".html"; //set url as "Clicked 'go' value + .html" (374.html"
$('#boo').fadeOut(600, function() { window.location.href = url; }); //fadeOut what is with the 'boo' id (body), and load the created address as a new page (?)
});
});
</script>
<a id="go" value="374" href="#">Go to page 374</a>
the 374.html page is in the same folder. If possible, please explain what have i done wrong, and make it step by step. I'm new to jquery.
Thank you!
the .val() method only applies to fields, just putting a value attribute on any element will not be read with the val() method.
Instead use .attr('value').
Or, its better practice to use data-* attributes and use the data() method:
<script type="text/javascript">
$(document).ready(function(){
$('#go').click(function(e) { //When something with the id 'go' is clicked,
e.preventDefault(); //Prevent default action (?)
var url = $('#go').data('value') + ".html"; //set url as "Clicked 'go' value + .html" (374.html"
$('#boo').fadeOut(600, function() { window.location.href = url; }); //fadeOut what is with the 'boo' id (body), and load the created address as a new page (?)
});
});
</script>
<a id="go" data-value="374" href="#">Go to page 374</a>
The val() function won't give you that value from an anchor tag, use attr("value") to get the valuue of the a tag
$(document).ready(function(){
$('#go').click(function(e) {
e.preventDefault();
var url = $('#go').attr("value") + ".html";
alert(url)
$('#boo').fadeOut(600, function() {
window.location.href = url;
});
});
});​
Alternatively, you can use HTML 5 data attribute to store such kind of value
<a id="go" data-someValue="374" href="#">Go to page 374</a>
And you can access it in javascript like
var someVal=$("#go").data("someValue");
sample http://jsfiddle.net/LyPZB/1/
The a tag doesn't support the attribute value, you should do like this:
set the anchor like this
<a id="go" data-page="374" href="#">...
(data-xxx are custom attributes)
and get its value with
$('#go').data('page')
In this way it will work and you will respect the HTML standard (since the anchor shouldn't have the value attribute)
Try:
var url = $('#go').attr("value") + ".html";
instead of
var url = $('#go').val() + ".html";
From the jQuery docs -
The .val() method is primarily used to get the values of form elements
such as input, select and textarea. In the case of elements, the .val() method returns an array
containing each selected option; if no option is selected, it returns
null.
There's an example here - http://jsfiddle.net/A8ArH/

Get HREF property

<a class="some" id="1" href="/s/1/2">link 1</a>
<a class="some" id="2" href="/s/2/3">link 1</a>
<script>
$(document).ready(function() {
$('.some').click(function() {
var id = this.id;
var link = $(this).css('href');
alert(id);
alert(link);
return false;
});
});
</script>
When I click on the link I get correct id, but "undefined" link. What is the problem and how can I fix it?
Change
var link = $(this).css('href');
to
var link = $(this).attr('href');
.css() is used to get/set CSS properties, .attr() is used to get/set attributes on elements.
You need to access the elements attribute, not CSS property :-)
var link = $(this).attr('href');
Use attr():
var link = $(this).attr('href');
Or simply:
var link = this.href;
Your code should look like:
$(document).ready(function() {
$('.some').click(function() {
var id = this.id;
var link = this.href;
alert(id);
alert(link);
return false;
});
});

Categories

Resources