How to disable a html link to instead call a JS function? - javascript

Having a text with annotations linking my text to dbpedia, I wanted to know if an effective way exists in Javascript for, by clicking on the link, to display a div with selected dbpedia information, rather than arriving on the page on the link ?
I am looking for some kind of "display none" on the link to allow me to display my div. I can not find this method, does it exist?
Furthermore, the links in my text are generated dynamically thanks to an Ajax request, and that they do not have id or class.
Here is one of my links in my text:
<a href="http://dbpedia.org/resource/Lorem_ipsum" title="http://dbpedia.org/resource/Lorem_ipsum" target="_blank" on>Lorem Ipsum</a>

Because the links are dynamically created you should use event delegation to get them. You can use an attribute selector to look only for links that start with a particular substring. Then use preventDefault to disable the link prior to using AJAX to grab the information and add it to a modal.
$(document).on('click', 'a[href^="http://dbpedia.org"]', function (e) {
e.preventDefault();
// load data from your source
});
DEMO
The non-jQuery version would look something like this:
document.addEventListener('click', handleClick, false);
function handleClick(e) {
const el = e.target;
if (el.tagName === 'A' && el.href.startsWith('http://dbpedia.org')) {
e.preventDefault();
// Do things
}
}
DEMO

Related

Prevent navigation and get the target link

I want to make my website faster by changing the content code via Ajax instead of navigating and reloading the page. But I also care about non-Javascript users so I want to use normal links instead of onclick event. And I want to prevent navigating and getting the target href link to change the content.
Is there a way to achieve that with Javascript/jQuery? Apparently jQuery supports event.preventDefault(); but I don't think it gives you an ability to get target link from that event...
This can be done in JavaScript (without using jQuery)
To catch all the clicks in document you can use
document.body.addEventListener('click', function(e) {
e.preventDefault()
const href = e.target.href
})
also you should add additional check that clicked element is exactly a link with href:
e.target.tagName.toLowerCase() === 'a'
So an example of working code:
document.body.addEventListener('click', function(e) {
if (e.target.tagName.toLowerCase() === 'a') {
e.preventDefault()
const href = e.target.href
}
})
With this function you will be able to catch all the clicks, check, if user clicked on a and get href attribute with just plain javascript. http://youmightnotneedjquery.com
Update
Based on #AVAVT comment if you need to handle case with something nested inside a, like
<a href="https://google.com">
<img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png?v=9c558ec15d8a">
</a>
just use e.target.closest('a')
document.body.addEventListener('click', function(e) {
if (e.target.closest('a')) {
e.preventDefault()
const href = e.target.closest('a').href
}
})
because target property will lead to exactly clicked item (in this case img) we need to check is it a child of a and then prevent default behavior.
Note:
jQuery solution is simple, so it's preferred, if you already have jQuery on the page.
Otherwise you can go without it with plain javascript.
I think jQuery's .attr() can help you:
$('body').on('click', 'a', function(e){
e.preventDefault();
doSomethingWith($(this).attr('href'));
});

use selectors in variable jquery

i have to made functionality like this on click of a link it will show the product details in a popup like box
this is using a big jquery code i didn't understand
and here is my jsfiddle
i am trying to give some links same class with different #tags to show the div
and i want that when i click on link it resolves the href value of the same and show the corresponding result but it didnt works
can somebody suggest the right way
here is my JS
$(".show").click(function() {
var link = $('this').attr('href');
$(link).show();
});
and html
a
b
c
i want to show #popup on anchor click
full code on fiddle and i want this functionality
You should call $(this), not $('this')
$(this) wraps the object referred to by this inside a jQuery object,
$('this') will traverse all of your document looking for html nodes tagged this (much like $('div') will look for html nodes tagged div); since there isn't any, it will select an empty list of nodes.
Working fiddle : http://jsfiddle.net/Hg4zp/3/
( there also was a typo, calling .hide(") instead of .hide() )
Try this way:
$(".show").click(function (e) { //<-----pass the event here
e.preventDefault(); //<--------------stop the default behavior of the link
var link = $(this).attr('href'); //<-remove the quotes $(this)
$(link).show();
});
$(".close").click(function () {
$(this).closest("div.popupbox").hide(); //<----use .hide(); not .hide(");
});
You should use preventDefault() in these cases to stop the jump which take place when a link get clicked.

using preventDefault() with on() in jQuery AJAX tabs

I have a set of jQuery UI AJAX tabs that load individual .php pages when they are clicked. All of my styling, etc. conveys, because the pages that hold the tabs widget provide the already linked CSS, and scripts. When it comes to the actual pages that load when clicking on the tabs however, I can't seen to get preventDefault() to work with .on() on these newly created DOM elements.
I'm using jQuery BBQ with my tabs so I can't have "#"s being appended to the URL. This is caused when links within the tab panels are clicked.
I've been able to successfully use preventDefault() on DOM elements that are initially loaded, but not ones that are being fetched into the tabs widget via AJAX.
My function for a content toggler is...
$(function(){
$(".showMoreOrLess").on('click', (function() {
if (this.className.indexOf('clicked') != -1 ) {
$(this).removeClass('clicked');
$(this).prev().slideUp(500);
$(this).html("Read More" + "<span class='moreUiIcon'></span>");
}
else {
$(this).addClass('clicked');
$(this).prev().slideDown(500);
$(this).html("See Less" + "<span class='lessUiIcon'></span>");
}
}));
});
I'd like to combine the preventDefault() from this function into it.
// prevents default link behavior on BBQ history stated tab panels with "showMoreOrLess" links
$(".showMoreOrLess").click(function (event)
{
event.preventDefault();
//here you can also do all sort of things
});
// /prevents default behavior on "showMoreOrLess" links
I've tried several ways using .on("click", function(work)), etc. I've used .on() in a separate function and also tried to combine it in the first function above. Does anyone know what I'm doing wrong? The code works on tab content that is static, just not content loaded via AJAX. Any help would be greatly appreciated. Can't seem to figure this out. Thanks in advance.
the part $(".showMoreOrLess").click just applies to already accessable links on your page
try to use event delegation (here the clicks are captured on an every time existing element and you just pass the selector it is watching for... as a nice side effect you save listeners
$(document).on("click", ".showMoreOrLess", function(event) {
event.preventDefault();
//here you can also do all sort of things
});
rather than document use a certain id from your page $("#myContainerId") (EDIT: of course the elements you are clicking on need to be inside of the element with the id)
$("body").on('click', ".showMoreOrLess", function(event) {
event.preventDefault();
var self = $(this);
if (self.hasClass('clicked')) {
self.html("Read More" + "<span class='moreUiIcon'></span>").removeClass('clicked').prev().slideUp(500);
}else {
self.html("See Less" + "<span class='lessUiIcon'></span>").addClass('clicked').prev().slideDown(500);
}
});

A way to pass variables (record ids) to jQuery event listeners?

Suppose I generate a list of records on my web page via PHP, and suppose each has a link beside it. And let's say that a modal window pops up when I click the link, and an edit form then shows in the modal.
I could easily make this happen like this:
Edit
But I'd prefer to use a jQuery event listener:
<a class="edit" href="#">edit</a>
$('.edit').click(function(event) {
showEditModal(recordId);
});
As you can see, using an event listener, I do not have a way of knowing which record the user wants to edit via the modal.
How can I allow the user to specify which record to edit while still using an event listener for the edit links?
If using jQuery >= 1.4.3, you can specify a "data-id" attribute (HTML5! woohoo) on the link and grab it using jQuery's data() method:
<script>
$(function() {
$('a.edit').click(function() {
alert( $(this).data('id') );
});
});
</script>
edit
And here's a demo on jsFiddle.
Put the ID in an attribute of the element.
<a class="edit" href="#12345">edit</a>
$('.edit').click(function(e) {
e.preventDefault();
recordId = $(this).attr("href").substr(1);
showEditModal(recordId);
return false;
});

jQuery DIV click, with anchors

To make click-able divs, I do:
<div class="clickable" url="http://google.com">
blah blah
</div>
and then
$("div.clickable").click(
function()
{
window.location = $(this).attr("url");
});
I don't know if this is the best way, but it works perfectly with me, except for one issue:
If the div contains a click-able element, such as
<a href="...">, and the user clicks on the hyperlink, both the hyperlink and div's-clickable are called
This is especially a problem when the anchor tag is referring to a javascript AJAX function, which executes the AJAX function AND follows the link in the 'url' attribute of the div.
Anyway around this?
If you return "false" from your function it'll stop the event bubbling, so only your first event handler will get triggered (ie. your anchor will not see the click).
$("div.clickable").click(
function()
{
window.location = $(this).attr("url");
return false;
});
See event.preventDefault() vs. return false for details on return false vs. preventDefault.
$("div.clickable").click(
function(event)
{
window.location = $(this).attr("url");
event.preventDefault();
});
Using a custom url attribute makes the HTML invalid. Although that may not be a huge problem, the given examples are neither accessible. Not for keyboard navigation and not in cases when JavaScript is turned off (or blocked by some other script). Even Google will not find the page located at the specified url, not via this route at least.
It's quite easy to make this accessible though. Just make sure there's a regular link inside the div that points to the url. Using JavaScript/jQuery you add an onclick to the div that redirects to the location specified by the link's href attribute. Now, when JavaScript doesn't work, the link still does and it can even catch the focus when using the keyboard to navigate (and you don't need custom attributes, so your HTML can be valid).
I wrote a jQuery plugin some time ago that does this. It also adds classNames to the div (or any other element you want to make clickable) and the link so you can alter their looks with CSS when the div is indeed clickable. It even adds classNames that you can use to specify hover and focus styles.
All you need to do is specify the element(s) you want to make clickable and call their clickable() method: in your case that would be $("div.clickable).clickable();
For downloading + documentation see the plugin's page: jQuery: clickable — jLix
I know that if you were to change that to an href you'd do:
$("a#link1").click(function(event) {
event.preventDefault();
$('div.link1').show();
//whatever else you want to do
});
so if you want to keep it with the div, I'd try
$("div.clickable").click(function(event) {
event.preventDefault();
window.location = $(this).attr("url");
});
<div class="info">
<h2>Takvim</h2>
Click Me !
</div>
$(document).delegate("div.info", "click", function() {
window.location = $(this).find("a").attr("href");
});

Categories

Resources