Get url before leave page - javascript

I have one web site with many random href <a> tags which used to redirect to another page. Is it possible to get which page the browser is trying to redirect when click the links with javascript and set return false and open that page with ajax and show it in a DIV? I am already trying with onclick but i need another easy way if possible.
Any answer appreciated.

<a href="link1" onclick="return false;" />Link A</a>
<a href="link2" onclick="return false;" />Link B</a>
<a href="link3" onclick="return false;" />Link C</a>
<a href="link4" onclick="return false;" />Link D</a>

<div id="links">
<a href="imalink-a" />Link A</a>
<a href="imalink-b" />Link B</a>
</div>
<div id="content"></div>
$('#links').on('click','a',function(e){
e.preventDefault();
var link = $(this).prop('href');
console.log(link);
$( "#content" ).load( link );
});

yes it's possible.
$("a").on('click', function(e){
// avoid the normal function of the <a>
e.preventDefault();
var href = $(this).attr("href");
console.log(href);
var current_location = $(location).attr('href');
console.log(current_location);
//make your ajax request here
$("#google").load(href);
});

$("a").on('click',function(){
event.preventDefault();
url=$(this).attr('href');
});
try this

http://jsfiddle.net/upsidown/J3Nvu/
$(".popup").click(function(e) {
// Prevent browser from following the link
e.preventDefault();
// Get the href attribute value
var url = $(this).attr("href");
// Display it or do what you want here
$("#result").html("Clicked " + url);
});

Link A
Link B
<div id="AjaxDiv"></div>
<script type="text/javascript">
function AjaxLoad(URL)
{
$("#AjaxDiv").load(URL);
}
</script>
**OR**
<div>
<a href="javascript:void(0);" data-href="demo.aspx" class="ajaxload" />Link A</a>
<a href="javascript:void(0);" data-href="2_demo.aspx" class="ajaxload" />Link B</a>
</div>
<div id="AjaxDiv"></div>
<script type="text/javascript">
$(document).ready(function() {
$(".ajaxload").click(function() {
$("#AjaxDiv").load($(this).attr("data-href"));
});
});
</script>

Related

Run javascript when anchor is clicked in the footer tag?

Here's my footer html:
<footer>
<div>
<a href='a.aspx'>test 1</a>
<a href='b.aspx'>test 2</a>
</div>
<a href='c.aspx'>test 3</a>
<footer>
Is there a way to always run a javascript function whenever a link is clicked within <footer> before it redirects? And is it possible to also find where it will redirect to within the function?
Sure. .querySelectorAll is perfect selector for this.
var footerAnchors = document.querySelectorAll("footer a");
footerAnchors.forEach(anchor => addClickListener(anchor));
function addClickListener(anchor){
anchor.addEventListener('click', (event) => {
alert(event.target.href);
event.preventDefault()
})
}
<footer>
<div>
<a href='a.aspx'>test 1</a>
<a href='b.aspx'>test 2</a>
</div>
<a href='c.aspx'>test 3</a>
<footer>
you can use querySelectorAll and forEach for this:
document.querySelectorAll("footer a").forEach(function(elem) {
elem.addEventListener("click", function(event) {
event.preventDefault() //use this to stop the default redirect if you want to do that manually
const linkTarget = event.target.href
console.log(linkTarget) //use this however you like
if (linkTarget.includes("a.aspx"))
document.location = linkTarget //for example redirecting if it contains a.aspx
});
});
<footer>
<div>
<a href='a.aspx'>test 1</a>
<a href='b.aspx'>test 2</a>
</div>
<a href='c.aspx'>test 3</a>
<footer>
however, if you want to execute a function every time the site is left, not only by clicking a link, but also by clicking back in the browser for example, i suggest you use window.onbeforeunload for this, instead of event handlers in the footer: docs
You don't need to attach listeners to every anchor element.
Using event delegation you can attach a single event listener to the footer element, and in the callback function check whether or not the clicked element was an anchor — then execute code related to each specific case.
Element.matches() can be used to check if the element that was clicked was an anchor, and then Event.preventDefault() can be used to prevent the default navigation behavior for the clicked anchor.
Here's a complete example:
const footer = document.querySelector('footer');
function handleFooterClick (ev) {
console.clear();
// The click event was dispatched from an anchor element:
if (ev.target.matches('a')) {
// Prevent the default anchor navigation:
ev.preventDefault();
console.log('You would have navigated to:', ev.target.href);
}
else { // Not an anchor:
console.log('You clicked another element:', ev.target.tagName);
}
}
footer.addEventListener('click', handleFooterClick);
<footer>
<h2>heading</h2>
<div>
<a href='a.aspx'>test 1</a>
<a href='b.aspx'>test 2</a>
</div>
<a href='c.aspx'>test 3</a>
</footer>

Jquery open this link not the others

So, I have a series of divs and inside each div there is a link.
What I want to accomplish is to open in another window or tab the .pdf file if the link ends in.pdf if not do nothing or something else to decide later.
The problem I'm having is that when you click on the link it will open the same document as many times as you have .pdfs on the page.
I tried replicating the problem in this fiddle:
https://jsfiddle.net/x9fo6cgk/
But it isn't working. The code works on my side.
Here is the code:
$('.somelink').click(function(eventObject) {
var elem = $(this);
if (elem.attr("href").match(/\.pdf$/i)) {
eventObject.preventDefault();
elem.attr('target', '_blank');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="linkholder">
<a class="somelink" href="https://bitcoin.org/bitcoin.pdf">pdf 1</a>
</div>
<div class="linkholder">
<a class="somelink" href="http://www.pdf995.com/samples/pdf.pdf">pdf 2</a>
</div>
<div class="linkholder">
<a class="somelink" href="http://www.bing.com">.com</a>
</div>
<div class="linkholder">
<a class="somelink" href="http://www.google.org">.org</a>
</div>
Thanks in advance!
You should just change the targets on page load if they are PDFs.
$('.somelink').each(function() {
var elem = $(this);
if (elem.attr("href").match(/\.pdf$/i)) {
elem.attr('target', '_blank');
}
});
JSFiddle: https://jsfiddle.net/x9fo6cgk/3/
Results in this HTML:
<div class="linkholder">
<a class="somelink" href="https://bitcoin.org/bitcoin.pdf" target="_blank">pdf 1</a>
</div>
<div class="linkholder">
<a class="somelink" href="http://www.pdf995.com/samples/pdf.pdf" target="_blank">pdf 2</a>
</div>
<div class="linkholder">
<a class="somelink" href="http://www.bing.com">.com</a>
</div>
<div class="linkholder">
<a class="somelink" href="http://www.google.org">.org</a>
</div>
Note: Your JSFiddle did not have jQuery selected so nothing ran.
You can do like this:
$('.somelink').click(function(eventObject) {
var elem = $(this);
if (elem.attr("href").match(/\.pdf$/i)) {
eventObject.preventDefault();
window.open(elem.attr('href'));
}
});
Look here: https://jsfiddle.net/x9fo6cgk/6/
For some reason the behavior of this script:
https://learn.jquery.com/events/event-basics/#preventdefault
under Magnolia CMS acts a bit weird.
So this code was used instead:
$(".linkholder a[href$='pdf']").attr('target','_blank').addClass('pdf');
$(".linkholder a:not(a[href$='pdf'])").addClass('generic');
Here is a the fiddle:
https://jsfiddle.net/x9fo6cgk/13/
Thanks everyone!

jQuery: Add Parent's ID to Child's rel

I'm trying to add the paren't ID to its child's rel. I'd like this
<div id="gallery-1>
<a href="">
<a href="">
</div>
<div id="gallery-2">
<a href="">
<a href="">
</div>
to look like this:
<div id="gallery-1" class="gallery">
<a href="" rel="gallery-1">
<a href="" rel="gallery-1">
</div>
<div id="gallery-2" "class="gallery">
<a href="" rel="gallery-2">
<a href="" rel="gallery-2">
</div>
My code:
$('.gallery a').attr('rel', $(this).parent('.gallery').attr('id'));
You need to put the code into a callback. Otherwise, it's called in the original function, not for each element in the collection.
$(".gallery > a").attr("rel", function() {
return $(this).parent().attr("id");
});
Try this:
$("div").each(function(){
var $this = $(this);
var id = $this.attr("id");
$this.children().attr("rel", id);
});
https://jsfiddle.net/0tr5wem0/

Repeating ID uses in javascript

I have a following set up:
<a href="#" id="A" >My Site</a>
<a href="#" id="A" >Your Site</a>
<a href="#" id="A" >Her site</a>
<a href="#" id="A" >His Site</a>
<a href="#" id="A" >Our Site</a>
And a button:
<a href="#" id="B" >Yay</a>
Then following javascript:
<script>
jQuery("#A").click(function()
{ jQuery("#B").trigger('click');
return false; });
</script>
In this setting, when "A" is clicked, then "B" is clicked as well.
It works well for the very first button ("My Site"). However other buttons are not working as if only the first id was recognized by the javascript and rest are simply ignored.
I mean, I can change the id of other buttons and repeat the javascript, however that seems like a poorly written idea.
What would be the best way of dealing in this situation? (a clean and efficient way).
Also, let say that I do have repeating javascript with different id as example below (for different buttons to trigger different buttons).
<script>
jQuery("#A").click(function()
{ jQuery("#B").trigger('click');
return false; });
jQuery("#C").click(function()
{ jQuery("#D").trigger('click');
return false; });
jQuery("#E").click(function()
{ jQuery("#F").trigger('click');
return false; });
</script>
In this case, is there a way for me to condense the repeating javascripts?
Thanks!
Your HTML is invalid. ID must be unique. JS will take first element with that ID and will ignore rest elements. Use classes for that.
$(document).ready(function() {
$('.A').click(function(e) {
e.preventDefault();
$('#B').trigger('click');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
My Site
Your Site
Her site
His Site
Our Site
<hr/>
<button onClick="alert('Clicked B')" id="B">Maybe clicked</button>
If you have to make reference what element must be clicked and your links does not have any link to other page, you can use it's href element:
$(document).ready(function() {
$('.A').click(function() {
$($(this).attr('href')).trigger('click');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
My Site
Your Site
Her site
His Site
Our Site
<hr/>
<button onClick="alert('Clicked A')" id="a">Maybe A clicked</button>
<button onClick="alert('Clicked B')" id="b">Maybe B clicked</button>
<button onClick="alert('Clicked C')" id="c">Maybe C clicked</button>
ID of an element must be unique so you can use a class to group similar elements, use a data-* attribute to specify which element's click has to be triggered.
A unique identifier for the element. There must not be multiple
elements in a document that have the same id value.
<a href="#" class="click" data-target="a" >My Site</a>
Your Site
Her site
His Site
Our Site
<a href="#" id="a" >Yay</a>
<a href="#" id="b" >Yay</a>
<a href="#" id="c" >Yay</a>
then
$('.click').click(function(){
$('#' + $(this).data('target')).click();
})
In HTML ID must be unique,You can enclose all anchors inside a block element and do like as follows
<div id="A">
My Site
Your Site
Her site
His Site
Our Site
</div>
Button
<a href="#" id="B" >Yay</a>
Script
<script>
jQuery("#A a").click(function()
{
jQuery("#B").trigger('click');
return false;
});
</script>
The id of an element has to be unique. Thus, I would suggest using a class:
<a href="#" class="A" >My Site</a>
<a href="#" class="A" >Your Site</a>
<a href="#" class="A" >Her site</a>
<a href="#" class="A" >His Site</a>
<a href="#" class="A" >Our Site</a>
Then:
elements = document.getElementsByClassName("A");
for(var i = 0; i < elements.length; i++){
var ele = elements[i];
jQuery(ele).click(function()
{ jQuery("#B").trigger('click');
return false; });
}

Efficent function replaceWith for multiple classes

The second "click" function of this script doesn't work, I think it's simply a syntax issue. I'm quite new to this. But I need to find a simple way call the live "click" function once for an array of vars.
The script works, just not the second part.
I'm looking for an efficient way to replaceWith an array of different vars, each matching a classed link, and without creating a new function every time.
Any suggestions would be great!
Thanks in advance
<script type="text/javascript">
$(window).load(function(){
$('a.pow').live("click",function(e) {
webgl = $('<iframe src="http://s..."> </iframe>');
e.preventDefault();
$('#slider-wrapper').replaceWith(webgl);
});
$('a.biff').live("click",function(e) {
video = $('<iframe src="http://s..."> </iframe>');
e.preventDefault();
$('#slider-wrapper').replaceWith(video);
});
});
</script>
html
<div id="slider-wrapper">
<div>
<a class="pow" href="">
</a>
</div>
<div>
<a class="biff" href="">
</a>
</div>
next one could be..
<div>
<a class="batman" href="">
</a>
</div>
</div><-- close slider wrapper -->
You can give all your anchors that will load iframes a common class, move the description of the anchor from class to a custom attribute, and have the event handler to act on the custom attribute instead.
<div id="slider-wrapper">
<div>
<a class="link" href="" data-desc="pow">
</a>
<div>
<div>
<a class="link" href="" data-desc="biff">
</a>
<div>
<div>
<a class="link" href="" data-desc="batman">
</a>
<div>
</div>
And in your script:
<script type="text/javascript">
var desc_url_map = {
"pow" : "http://s...",
"biff" : "http://s...",
"batman" : "http://s..."
};
$(window).load(function () {
$('a.link').live('click', function(evt) {
item = $('<iframe src="' + desc_url_map[this.dataset.desc] + '"></iframe>');
$('#slider-wrapper').replaceWith(item);
evt.preventDefault();
});
});
</script>
Hope there are no bugs :)

Categories

Resources