JavaScript Event Handler jQuery - javascript

I am working on a hand me down project that was written by someone who was clearly better at HTML and JavaScript than myself. The html has AJAX links like this:
<ul class="subNav">
<li><a link="contacts.html">Contacts</a></li>
<li><a link="contacts_add.html">Add Contact</a></li>
</ul>
Which I think are handled in this code:
$('.subNav li a').click(function() {
var href = $(this).attr('link')
$('#mainStage').load(href, function() {
pageLoad();
})
})
All of the code above works perfectly.
My problem is I can't seem to recreate this functionality. I am using this HTML:
<div class="nameTitle colorOne"><a link="contacts_add.html">
<span class="firstNameField">Contact Name</span>
</a></div>
and this JavaScript:
$('.nameTitle').click(function() {
alert('')
$('#mainStage').load("contacts_add.html", function() {
pageLoad();
})
})
When I click the "nameTitle" class it should load contacts_add.html into the mainStage section of the page but I cannot see anything happen. I am sure someone fluent with this style of coding could tell me why my event never fires but the earlier code does.
Thanks in advance,

You should try altering your code to something like this:
$('.nameTitle').click(function() {
//This line finds the address to load
var address = $(this).children("a").attr("link");
//This line loads the address and then runs the pageLoad function when it has completed
$('#mainStage').load(address, function() {
pageLoad();
});
});
If this doesnt work it may be because the html is loaded dynamically. In this case you need to use .on, see this link here.
In response to Brett's comment below ive put together a jsfiddle showing .on in action here. Also i added .preventDefault as this could cause a problem.

try with
$('.nameTitle a').click(function() {
It can be that you're trying with a browser which accepts click only on 'a' tags, albeit they're getting rare hopefully.

The 'click' event will never be raised on your div, since there is an inner a element with an href defined. Once you click, the event will be raised on the anchor link first which will, by default, redirect to the location specified by the href. In order to get this working, catch the click when it is raised at the a:
$('.nameTitle a').click(function(e) {
e.preventDefault(); // prevent browser from following href
alert('');
$('#mainStage').load("contacts_add.html", function() {
pageLoad();
});
});
Demo -- Commented out the load, since that page isn't on this server. Also notice I changed your a element to have attribute href instead of link.

Related

Jquery click event of anchor tag not working

I am unable to fire the click event on an <a> tag which is inside the div tag.
Here is my JSP code for UI
<div class="container" id="userHeader">
<c:choose>
<c:when test="${isLogin}">
<ul>
<li>Hello ,${user.name}</li>
<li> Call : **********</li>
<li>xyz#gmail.com</a></li>
<li><a id="logout">Sign Out</a></li>
</ul>
</c:when>
<c:otherwise>
<ul>
<li>Sign In </li>
<li>Sign Up </li>
<li>Call : *********</li>
<li>xyz#gmail.com</li>
</ul>
</c:otherwise>
</c:choose>
</div>
Clicking on "sign in" will open a form and that form is submitted and validated perfectly. After "sign in", the logout tag will appear on the screen instead. No, clicking on "sign out" doesn't work. $("#logout"), click hander is not even fired.
Here is the JQuery and JS part of the code:
$(document)
.ready(
function() {
// SUBMIT FORM
$("#signInForm").submit(function(event) {
event.preventDefault();
signInAjaxPost();
});
function signInAjaxPost() {
// PREPARE FORM DATA
// do ajax request and set html
}
// **The logout anchor tag handler for sign out (This is not working , its not even fired)**
$('#logout').click(function (e) {
debugger;
e.preventDefault();
signOutPost();
});
function signOutPost() {
//sign out code
}
});
Now, if I write the $(#logout) click handler on browser console along with the function inside, it works. Thus, after writing the same code on browser console and clicking the anchor tag again the user is logged out. But why does this event is not fired without writing on browser console. I checked the DOM scripts for JS. The code is loaded onto the browser, it's not like code is missed in the build.
I have searched throughout, unable to find a solution or even root cause to this problem.
As far as I understand, the logout link is added to the DOM dynamically, and that's why the event handler for $('#logout').click isn't bound to the specified element.
One way to mitigate this is to use on() which applies the event binding to the future objects as well. Try the following:
$('#userHeader').on('click', '#logout', function(e) {
e.preventDefault();
signOutPost();
});
If your #logout element does not exist on page load, then you need to specify your click statement like this:
$("#userHeader").on("click", "#logout", function(e) {
debugger;
e.preventDefault();
signOutPost();
});
A standard jQuery .click will not work if the element does not exist when the page loads.
You can try event-delegation, because #logout element not loaded in DOM because of your condition
check documentation : http://api.jquery.com/on/
$('#userHeader').on('click',"#logout",function (e) {
// code
});

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 Class selector not working

I'm struggling to make an alert come up when an anchor tag with a specific class is clicked inside of a div.
My html section in question looks like this...
<div id="foo">
<a class='bar' href='#'>Next</a>
</div>
The jQuery section is as follows..
$('.bar').click(function()
{
alert("CLICKED");
});
My problem is that I cannot get this alert to come up, I think that I'm properly selecting the class "next", but it won't pick it up for some reason. I've also tried almost everything on this page but nothing is working. If I don't try to specify the anchor tag i.e. $('#foo').click(function()... then it works, but there will be multiple anchor tags within this div, so simply having the alert executed when the div is clicked won't work for what I need. The website this is on is a search engine using ajax to send information to do_search.php. Within the do_search.php I make pagination decisions based on how many results are found, and if applicable, a next, previous, last, and first link may be made and echoed.
EDIT: I just figured it out, it was my placement of the .next function, since it wasn't created on the initial document load but instead after a result had been returned, I moved the .next function to the success part of the ajax function since that is where the buttons will be created if they need to be, now it works.
Try using the live() command:
$(".bar").live("click", function(){ alert(); });
Because you load your button via AJAX, the click event isn't binded to it. If you use the live() command, it will automatically bind events to all elements created after the page has loaded.
More details, here
.live is now deprecated and is the selected answer for this. The answer is in the comments in the selected answer above. Here is the solution that resolved it for me:
$(document).on('click','.bar', function() { alert(); });
Thanks to #Blazemonger for the fix.
You surely missed $(document).ready(). Your code should be:
$(document).ready(function(){
$('.bar').click(function()
{
alert("CLICKED");
});
});
Hope this helps. Cheers
Make sure you have included JQuery Library properly.
Make sure your script has written between $(document).ready() in short $(function(){ });
Demo : http://jsfiddle.net/W9PXG/1/
<div id="foo">
<a class='bar' href='#'>Next</a>
</div>
$(function(){
$('a.bar').click(function()
{
alert("CLICKED");
});
});

jQuery "after-click" event

I have a list of links that open in an iframe, like:
<ul id="frameTrigger">
<li><a target="iframe1" href="aaa.html"><img src="aaa.jpg"></a></li>
<li><a target="iframe1" href="bbb.html"><img src="bbb.jpg"></a></li>
<li><a target="iframe1" href="ccc.html"><img src="ccc.jpg"></a></li>
</ul>
I need to update another div after the link is clicked. Specifically, I need to call a function that checks the frame's src attribute and update the div. If I do a:
$("#frameTrigger a").click(function() {
var iframe = $("iframe[name=iframe1]").get(0);
console.log(iframe.contentWindow.location.href);
// the problem here is that that the iframe.window.location will
// change AFTER this function returns
});
I do not get what is expected.
I'm guessing you get the old value instead of the new one? You may want to wrap your function in a setTimeout of 1ms to allow the update to go through.
$("#frameTrigger a").click(function(){
console.log( $(this).attr("href") );
});
You need the first selector to work on clicks for the links. Also, I think you had the syntax for console.log incorrect (though I have never used it). I changed it so when you click on a link it logs the href attribute of the link. Hope this helps.
If you're having trouble with the entire click functionality completing when calling the click via jQuery .click() - I know it's not ideal, but - perhaps you should just have jQuery explicitly complete the sequence that should be executed when clicked. Something like:
$("#someElement").bind('click', function(event) {
event.preventDefault();
$($("#frameTrigger a:eq(1)").attr('target')).attr('src', $("#frameTrigger a:eq(1)").attr('href'));
});

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