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

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

Related

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

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

Link in jquery div stop working

when i click on gallery, and visit for example "paintings", the links on the menu stops working, why is this? can someone please tell me whats wrong -_-
http://madebysam.se/elbarco
This is the code im using
$(document).ready(function(){
$('a').on('click',function(){
var aID = $(this).attr('href');
var elem = $(''+aID).html();
$('.target').html(elem);
$('ul li').on('click',function(event) { event.stopPropagation(); })
});
});
Using dev tools and a breakpoint inside your example code snippet on your live site, I see that only the links loaded initially trigger your event handling code.
The problem is here:
$('a').on('click',function(){
// do stuff
});
The common pitfall is that you register this handler against all anchor tags that are loaded in the page at that moment. Any anchor tags dynamically added later will not enjoy that same event handler.
A workaround is to use a different syntax, targeting first a larger tag that is guaranteed to be there on first load, and then filter down to the anchor tags:
$('body').on('click', 'a', function(){
// do stuff
});

jQuery - .on('click') not working on <li>

so I've been tasked with making a website using Wordpress and on the homepage there's a slider that if you click on the buttons below, it's displays another image, simple right? Well, I've got the slider and I've got the buttons, I've added the jQuery and it doesn't want to work.
I first tried making the buttons actually buttons:
<button type="button" class="btn btn-success" id="hideshow-healthcare">Healthcare</button>
and that worked fine when I used this:
jQuery(document).ready(function() {
jQuery('#hideshow-healthcare').on('click', function() {
jQuery('#healthcare').show();
};
};
So after having it working like that, I moved on to making the buttons in to li's instead so that I could follow the design. Upon doing this, the slider no longer works. I've tried mulitple different things including adding the ID to everything in the li to see if that would work, and sadly not. I did some research and tried to change
jQuery('#hideshow-healthcare').on('click', function() {
to
jQuery('li#hideshow-healthcare').on('click', function() {
but still, no luck. I was hoping someone would be able to provide a solution to this problem.
Also, this is the li code I'm currently using:
<li><a id="hideshow-healthcare"><h5>HEALTHCARE</h5> Lighting to create a feeling of well being</a></li>
You need to add space after li element to find its descendants #hideshow-healthcare. It should be
jQuery('li #hideshow-healthcare').on('click', function() {
#hideshow-healthcare is child of li. Use descendant selector in jquery
jQuery('li a#hideshow-healthcare').on('click', function(event) {
event.preventDefault(); // prevents default action
// your code
});
Id be unique in html you just straightly write with id
jQuery('#hideshow-healthcare').on('click', function(event) {
event.preventDefault(); // prevents default action
// your code
});

Enabling default behaviour link by link with jquery

I am an html css design type who is not that comfortable with jquery. I have inherited a site with the link default behaviours disabled with what I can see is this code:
$('a').click(function(event) {
event.preventDefault();
var locationHref = window.location.href;
var elementClick = $(this).attr("href");
var destination = $(elementClick).offset().top;
$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, 1000, function() {
window.location.hash = elementClick
});
return false;
I need to add normal links to this one page website without messing with this code (it enables parallax scrolling). Is there any way I can do this link by link?
BTW I have seen solutions on here but I must confess to not quite understanding them. Thanks.
Not sure why anyone would blanket disable ALL links on a page in this way. Unfortunate that you've inherited such code. I wasn't sure if you meant you couldn't touch that code, or merely didn't want to.
If the former, you have two options:
1) Unbind this click event for certain links. For example, if you had links inside a container, #container, or all your links had a certain class, .class, you could do this:
$('#container a').off('click');
$('a.class').off('click');
These links would then be free of the inherited click event handler.
The only problem with this is you unbind all click event handlers bound to such links. Since the inherited event isn't namespaced, this is unavoidable. A second option is to...
2) Set up a second click event handler that bypasses the default action prevention of the inherited handler by forwarding users on to the link's HREF nonetheless:
$('a').on('click', function() { location.href = $(this).attr('href'); });
How about giving these special links a data-donthandle="true" attribute. Then, check for this attribute in the jQuery. If the attribute exists and is false, simply return true; at the beginning of the event handler.
This would save you looking through and disabling the onclick via javascript as already suggested.
$('a').click(function(event) {
if($(this).attr('data-donthandle')) {
return true;
}
else {
event.preventDefault();
//code here for handling clicks
alert('Stopped.');
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