jQuery replace all href="" with onclick="window.location=" - javascript

So I have a cool one for ya.
I need to scan my html document as it is rendering and replace every
href=""
with
onclick="window.location=''"
more than that, I need to carry the link from the href to the window.location.
For example, if I had:
href="http://www.google.com.au"
it would become:
onclick="window.location='http://www.google.com.au'"
and I need it to do this on every href in the document
I have no idea, but it needs to be in jQuery / javascript :D
Thanks guys.

You could try this:
$('a').each(function() {
var href = $(this).attr('href');
$(this).attr('onclick', "window.location='" + href + "'")
.removeAttr('href');
});
What are you trying to achieve with this? Chances are that there's a more elegant way to achieve what you're after.
For example, it might be better to handle the event yourself in the JS. Replace the third line with:
$(this).click(function() { window.location = href; })
That could become very expensive though, so you might want to consider jQuery's delegate events: http://api.jquery.com/delegate/

This should achieve what you want...
$('a[href]').click(function(event) {
event.preventDefault();
window.location = this.href;
});
I assume you wanted to prevent default behaviour of links.
For all possible links, you could use document.links.
For all links and future links, use event delegation.
$('body').on('click', 'a[href]', function() {
window.location = this.href;
});

Some non-jQuery variants:
Keep href:
var i = document.links.length;
while (i--)
document.links[i].onclick = function(){window.location = this.href;};
Keep href and don't follow it if onclick called (even though it goes to the same place):
var i = document.links.length;
while (i--)
document.links[i].onclick = function() {
window.location = this.href;
return false;
};
Remove href:
var i = document.links.length,
link;
while (i--) {
link = document.links[i];
link.onclick = (function(href) {
return function() {
window.location = href;
}(link.href));
link.href = '';
}
link = null;
Of course I don't understand why you want to replace a robust, works everywhere solution with an unreliable, easily broken one.

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');
});

replace matching text in hyperlink href

What im trying to do is find all hyperlinks that have a href like this herf="/grade4/chapter1.html"
and replace the chapter word with href="grade4/chapter_af1.html"
i have tried a few jquery tricks but have had no luck
$('a').each( function() {
var $this = $(this);
var href = $this.attr('href').replace(/\chapter/,'chapter_af');
$this.attr('href', href );
});
You don't need a regular expression, just do a normal string replace:
http://jsfiddle.net/9MXSZ/
$('a').each( function() {
var $this = $(this);
var href = $this.attr('href').replace('chapter','chapter_af');
$this.attr('href', href );
});
If you really want to use a regex, the \ in your version is throwing it off:
.replace(/chapter/,'chapter_af')
No need of Regex here.
Try simply like this
var href = $this.attr('href').replace('chapter','chapter_af');
Just change your replace statement to:
...
var href = $(this).attr('href').replace('chapter', 'chapter_af')
...
See it working here: http://jsfiddle.net/vNCpV/

jquery get href value and use it as a variable

So I have set up a scrolling code for my website.
<section class="fpage">
<a class="next" href="#view">test</a>
</section>
<section class="cpage">test</section>
In jquery I've got.
$(document).ready(function () {
$('.next').click(function (event) {
var cpage = $(this).find('a').attr('href');
var fpage = $(this).closest('section');
event.preventDefault();
fpage.addClass('anim').delay(500).queue(function(next){
$(this).removeClass().addClass('cpage');
next();
cpage.removeClass('.cpage').addClass('fpage');
});
});
});
I want the var:cpage to take the .next href value (in this case: #view) and use it as the name of it's variable. What have I dont wrong in this instance? And how can I turn the cpage var into #view?
.next is the a itself. you don't need to use .find
var cpage = $(this).attr('href');
OR
var cpage = this.href;
Edit : as cpage is an ID you need to do this to select the element
$(cpage).removeClass('.cpage').addClass('fpage');
As far as I understood, this should solve:
fpage.addClass('anim').delay(500).queue(function(next){
$(this).removeClass().addClass('cpage');
next();
$(cpage).removeClass('.cpage').addClass('fpage');
});
You have a few things out of place but all in all, no biggie.
First,
$('.next').click(function (event) {
var cpage = $(this).find('a').attr('href');
It can't call its self. .next is a class for the a tag, so how can a tag find inner elements with the a tag if it is the only a tag element? jQuery's .find works to find children and grandchildren and such of the element it's called upon. thus this line is just as easy written as:
var cpage = $(this).attr('href');
Second,
cpage.removeClass('.cpage').addClass('fpage');
cpage is only a string variable, not a jQuery object, thus it needs a slight change. Try:
$(cPage).removeClass
I don't know what version of jQuery you are using, but I gave your code a complete scrub down and edit and posted a jsFiddle using the latest jQuery's. Important to note, if you're using an older version, some things might be different, such as .on being .bind or .live in older versions.
jsFiddle
$(function() {
$(".next").on("click", function(e) {
e.preventDefault();
var cPage = $(this).attr("href"),
fPage = $(this).closest("section");
fPage.addClass("anim").delay(500).queue(function(n) {
$(this).removeClass().addClass('cpage');
n();
$(cPage).removeClass('.cpage').addClass('fpage');
});
});
})

Modify target url in onclick handler

Is it possible to modify the target URL in the onclick handler? How?
I don't want to use things like window.location = ... because it changes the browsers' behaviour (click vs ctrl-click, opening in new tab, opening in particular window/frame etc...). I want a clean solution - just change the url and the rest should be done itself as it would normally be.
$(...).click(function () {
if (check_some_condition)
// modify target url here...
// do not want to do window.location= - this is not clean
// as it changes the browsers' behaviour (ctrl-click, opening in particular window/frame etc.)
return true;
});
Try
​$(function(){
$("#theLink").click(function(){
$(this).attr("href","http://tnbelt.com");
});
});​​​​
Edit: Updated code because the event handler script is executed first and then the default action takes place.
Added below version to show you that you can use .click as you didn't notice the quirks mode link I shared with you. DEMO
$(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";
}
});
});
Commented e.preventDefault(); & $(this).click() as it is not required..
DEMO
$(document).ready (function () {
$('#changeMe').one ('click', function (e) {
//e.preventDefault();
this.href = "http://www.google.com";
//$(this).click();
});
});
Let us consider a hidden anchor tag
<a id="linkId" href="myPageToGo.html" class="thickbox" title="" style="visibility:hidden;">Link</a>
Then you can simulate the anchor click in your code...
$(...).click(function () {
if (check_some_condition)
$('#linkId').click();
return true;
});
EDIT - Alternative way
Wrap the element clicked inside a anchor tag...
$(...).click(function () {
if (check_some_condition)
$(this).wrap('<a id="new1" />');
$('#new1').click();
return true;
});
Yup.
$(this).attr('href', 'http://example.com/');
A lot of the answers including the top comment have missed out on an important point. If a user simply right clicks the URL to perhaps open in a new tab/window, this method won't work because you're directly requesting at the location specified by the 'href' URL instead of going through the onclick event.
You could try the same at this demo fiddle mentioned on Gourneau's post.
http://jsfiddle.net/skram/PtNfD/7/
$(document).ready (function () {
$('#changeMe').one ('click', function (e) {
this.href = "http://www.google.com";
});
});

Is there a way to override the browser's default behavior for clicking on hashes?

When I have the following:
<a name='test'></a>
...and load it in a browser, I can append #test to the URL and the browser will scroll so that the <a> is at the top of the page.
However, I would like to change this behavior (using JavaScript if possible) so that using the hash does not scroll the page - I'd like it to simply do nothing.
Is there a way to do that without removing the <a> element?
Update: I need the browser to still send onhashchange() events but without scrolling to the <a> element. The reason being that I want to override the scrolling while retaining the event notification.
A quick dirty hack, but it's something you can build upon:
var curScroll = prevScroll = $(window).scrollTop()
$(window).bind('scroll', function() {
prevScroll = curScroll
curScroll = $(this).scrollTop()
}).bind('hashchange', function() {
$(this).scrollTop(prevScroll)
})
I used jQuery here to make it work across browsers and keep the page's onhashchange and onscroll handlers intact. One problem I spotted is that if you click the same hashtag twice it scrolls anyway.
UPD. I just figured out a better solution:
$('a').live('click', function() {
if (this.href.split('#')[0] == location.href.split('#')[0]) {
var scrollTop = $(window).scrollTop()
setTimeout(function() {
$(window).scrollTop(scrollTop)
}, 0)
}
})
Well, you can try to be brutal:
var i, elems = document.getElementsByTagName('a');
for (i = 0; i < elems.length; i++) {
elems[i].removeAttribute('name');
}
It has to be run after the DOM is ready but before it gets rendered so you have to put it in the right place. It won't work for 'id' attributes - only with <a name=...>
Does it do what you want?
Try this:
$( 'a[href="#"]' ).click( function(e) {
e.preventDefault();
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
A kind-of hacky technique would be to just automatically scroll to the top of the page if there's a hash in the url:
if (window.location.hash) {
window.scrollTo(0, 0);
}
perhaps you need to use a bit of jquery and string manipulation
removeHashPartFromString = function() {
...
}
$('a').each(function() {
this.attr('href') = removeHashPartFromString(this.attr('href'));
});
Or find the elements with the hash and remove the name hash attributes from those elements.

Categories

Resources