jQuery click event with class selector only fires once - javascript

I'm using classed links to change FlowPlayer content. Here is a working version: http://jsfiddle.net/r9fAj/
In my actual page using the same code the first link clicked works fine. The second one does not fire the click function at all. Even if I comment out everything but the console.log()...
$('.playerLink').click( function() {
audioPlayer.unload();
initAudioPlayer();
$('#player').css('display', 'block');
$('#player').animate({"height":"50px"}, 1000);
var newClip = {'url':$(this).attr('ajax-data'),'autoplay':true};
audioPlayer.play(newClip);
console.log('playing ' + $(this).attr('ajax-data'));
});
HTML like so
Listen
Listen
<a id="flowplayer" href="/audio/episodes/09_27_2013_Happy_Hour_88509726.mp3"></a>
And the player initialized like so:
var audioPlayer;
var initAudioPlayer = function () {
$f("flowplayer", "/player/flowplayer-3.2.16.swf", {
plugins: {
controls: {
fullscreen: false,
autoHide: false,
}
},
clip: {
autoPlay: false,
url: "",
}
});
audioPlayer = $f();
};
initAudioPlayer();
Since the jsFiddle works over and over I assume something else in my page is preventing the second click() from working but the console has no errors for me.
So my question is, short of posting the whole site's code how do I pursue debugging this?

So it sounds like your .click() event handler is only being fired for the first link you click and not for additional clicks. For general debugging, you could take your page that is not working and gradually comment out / remove other part of the JS and HTML until you are able to make it work correctly. Or start with the minimal amount that is working (the fiddle) and gradually add in the rest to see when it stops working.

So this is the first site I have done where content is delivered via AJAX and internal links are caught by
$("a:not([href^='http://'])").click( function(e) {
var url = $(this).attr("href");
var title = ($(this).attr("title")) ? ': ' + $(this).attr("title") : '';
e.preventDefault();
if(url!=window.location){
window.history.pushState({path:url},title,url);
$('#contentMain').load(url);
document.title = "It's New Orleans" + title;
}
});
For some reason it does work once to click a link with the class but the second time gets preventDefault()ed.
Listen
The fix was adding [href^='#'] to not() e.g.
$("a:not([href^='http://'],[href^='#'])").click( function(e) {

Related

youtube spf is not working after loading with ajax

On my web page, everything is okay.
My js is working very well but clicking on any page, page is loading with ajax but some function is not working for example my bootstrap carousel or my parallax.js plugin..
How do I do event management ?
I'm using youtube spf plugin
some js example on my page
if (!$(".scene").length) return false;
var q = document.getElementsByClassName("scene")[0];
var r = new Parallax(q, {
calibrateX: false,
calibrateY: true,
invertX: false,
invertY: true,
limitX: false,
frictionX: .2,
frictionY: 4,
originX: 0,
originY: 1
});
$('.img-area').cycle({
fx: 'fadeout',
speed: 950,
timeout: 100
}).cycle("pause");
$(".otel-history-list").on("click",function(){
var historyName = $(this).find(".history-current-name").text();
var historyDateIn = $(this).find(".history-current-datein").text();
var historyDateOut = $(this).find(".history-current-dateout").text();
var historyKisi = $(this).find(".history-current-kisi").text();
$(".input-form-ara input").val(historyName);
$(".otel-giris-cikis #checkin").val(historyDateIn);
$(".otel-giris-cikis #checkout").val(historyDateOut);
$(".kisi-sayi-otel-sec .kisi-count").text(historyKisi);
});
or something like these code
and my ajax code
$(function () {
spf.init();
NProgress.configure({ showSpinner: false });
$(document).on('spfrequest', function (event) {
NProgress.set(0.4);
});
$(document).on('spfprocess', function (event) {
NProgress.set(0.6);
NProgress.set(0.8);
});
$(document).on('spfdone', function (event) {
NProgress.set(1.0);
NProgress.done();
});
$(document).on('spfhistory', function (event) {
NProgress.set(0.7);
NProgress.set(0.9);
NProgress.set(1.0);
NProgress.done();
});
});
and I'm using bootstrap,parallax.js,cycle2.js,select2 plugin
I've answered a similar question in the past, so I'm restating it below:
I'm not sure what your full code set is, but based on what you posted, I'm guessing that several of your html elements (that have JQuery event handlers attached to them) are generated and re-generated using your ajax functions-- probably several times, after your original DOM is loaded.
This is the most likely reason why some of your events don't fire after your Ajax codes fire. The event handlers attached to your html elements (such as divs) get "detached" when these elements are programmatically (re)generated using Ajax.
As such, what you would want to do is to "attach" the event handler to a higher level in the DOM tree (highest being your html) that you are sure won't get 'programmatically' regenerated, then you'd want to check if the element in question, which is inside the DOM, exists. You then run your function when this element is found.
So as an example, you have this onclick function in your code:
$(".otel-history-list").on("click",function(){
//your actions
});
The element with the class "otel-history-list" is likely being generated or regenerated by your Ajax call after page load, and as such would get detached from your onclick event listener (See #1-#2 above).
So to rewrite your code following #3 above, you'd want to attach the event listener to something that won't be regenerated by your Ajax, then just look for the specific element inside it, which contains your class of interest:
$(document).on("click",".otel-history-list", function(){
//your actions
});
Hope this helps!

How to hide the anchor tag element rapidly on the onclick event using jQuery?

I've two hyperlinks. I'm hiding the one hyperlink on the click of other hyperlink and vice-versa. It's working absolutely fine for me on my local machine. But the issue arises when I upload and run the same functionality from the online server.
On server, the concerned hyperlink is not hiding that much quicker as compared to local machine instance. Due to which user can click again on a hyperlink which he has already clicked and the link is expected to be hidden. It takes moment or two for hiding the concerned hyperlink. I don't want that delay. The hyperlink should get hide immediately after on click event. I tried disable/enable the hyperlink but it didn't work out for me.
My code is as below:
<script language="javascript" type="text/javascript">
$(".fixed").click(function(e) {
var action_url1 = $(this).attr('delhref');
var qid = $(this).data('q_id');
$(".fixed").colorbox({inline:true, width:666});
$("#fixedPop_url").off('click').on('click',function(event) {
event.preventDefault();
$.get(action_url1, function(data) {
//$("#fix_"+qid).bind('click', false);
$("#fix_"+qid).hide();//This portion of code I want to make fast, it's taking some time to hide and meanwhile user can click on this link. I want to avoid it.
$("#notfix_"+qid).show();
//$("#notfix_"+qid).bind('click', true);
alert("Question status updated successfully");
});
});
$(".c-btn").bind('click', function(){
$.colorbox.close();
});
});
$(".notfixed").click(function(e) {
var action_url2 = $(this).attr('delhref');
var qid = $(this).data('q_id');
$(".notfixed").colorbox({inline:true, width:666});
$("#notfixedPop_url").off('click').on('click',function(event){
event.preventDefault();
$.get(action_url2, function(data) {
//$("#notfix_"+qid).bind('click', false);
$("#notfix_"+qid).hide();//This portion of code I want to make fast, it's taking some time to hide and meanwhile user can click on this link. I want to avoid it.
$("#fix_"+qid).show();
//$("#fix_"+qid).bind('click', true);
alert("Question status updated successfully");
});
});
</script>
You dont have to write the hide part code in complete function of get request. On live it will take time to fetch the rspond.so just keep it outside get function.something like this:
$(".fixed").click(function(e) {
var action_url1 = $(this).attr('delhref');
var qid = $(this).data('q_id');
$("#fix_"+qid).hide();
//rest code......
});
$(".notfixed").click(function(e) {
var action_url2 = $(this).attr('delhref');
var qid = $(this).data('q_id');
$("#notfix_"+qid).hide();//hide it here
//rest code......
});

Disable a next/previous button(link) temporarily when clicked in jQuery Cycle plugin (not necessarily a jquery cycle issue)

I need to prevent link from being clicked for let's say 2 seconds.
Here is an example http://jsbin.com/orinib/4/edit
When you look at the rendered mode you see next and prev links. When you click next, it slides with a nice transition. However if you click multiple times there is no transition sort of, which is expected. But my question: is this how can I prevent clicking on the next link, for about 2 seconds (or what ever time it takes for transition to happen) so that no matter what transition will occur.
This is what I tried to use, but did not work:
function(){
var thePreventer = false;
$("#next").bind($(this),function(e){
if(!thePreventer){
thePreventer = true;
setTimeout(function(){
thePreventer = false;
}, 2000);
}else{
e.preventDefault();
}
});
}
Which I got from here "Disable" a link temporarily when clicked? I think. I believe that i cannot achieve this effect with this code (although it works on other links). I believe this is due to the fact that cycle-plugin got a hold of that link, and I understand that I have to bind/tap-into this functionality of the plugin. Please note: that this code may not work I just used it to show that I tried it and it did not work, you can reuse it if you have to or give me your own stuff.
Please help, if you can.
EDIT:
As mrtsherman proposed this simple yet elegant ANSWER: http://jsfiddle.net/LCWLb.
Take a look at the cycle options page. There are a number of ways to do this. I would consider using the pager event onPrevNextEvent. You can assign a callback function.
$('#slideshow').cycle({
pager: '#nav',
onPrevNextEvent: function(isNext, zeroBasedSlideIndex, slideElement) {
//disable controls
},
after: function(currSlideElement, nextSlideElement, options, forwardFlag) {
//reenable controls
}
});
The following will temporarily prevent clicks while a slideshow is running, as shown in this fiddle:
$.fn.extend({
delayClick: function(callback) {
this.bind('click', function(e) {
$self = $(this);
if( $self.hasClass('disabled') ) {
$('#log').append('<p>click prevented on '+$self.attr('id')+'</p>');
}
else {
$self.addClass('disabled');
callback.call(this, [arguments]);
setTimeout(function() {
$self.removeClass('disabled');
}, 1000);
}
return false;
});
}
});

How to Separate Two jQuery Functions

I want to separate these functions. They should both work separately on click events:
FIRST FUNCTION
$("ul.nav li").delegate("a", "click", function() {
window.location.hash = $(this).attr("href");
return false;
});
$(window).bind('hashchange', function(){
newHash = window.location.hash.substring(1);
if (newHash) {
ACTION A
});
$(window).trigger('hashchange');
});
SECOND FUNCTION
$("ul.subnav li").delegate("a", "click", function() {
window.location.hash = $(this).attr("href");
return false;
});
$(window).bind('hashchange', function(){
newHash = window.location.hash.substring(1);
if (newHash) {
ACTION B
});
$(window).trigger('hashchange');
});
This is what happend in ACTION A:
$mainContent
.find(".maincontent")
.fadeOut(200, function() {
$mainContent.hide().load(newHash + " .maincontent", function() {
$mainContent.fadeIn(200, function() {
$pageWrap.animate({
height: baseHeight + $mainContent.height() + "px"
});
});
$(".nav a").removeClass("active");
$(".nav a[href="+newHash+"]").addClass("active");
});
});
The Problem is that if I click the Link of the Second function always the the first function fires.
Details of what I'm trying to do:
First, I build my site on .php to serve poeple without JavaScript. Now I want to load the "maincontent" dynamically. So I found this script I'm using:
http://css-tricks.com/6336-dynamic-page-replacing-content/
It does do a great job if you only want to load "maincontents".
But my site has sub-navigation on some pages where I want to load the sub-content. In .php these sites use includes. So I get my content by: href="page2.php?page=sub1"
So, when I click on the sub-links now they load also dynamically but the script also on the whole maincontent loading area. So it doesn't really load content by .load() but the sub-content of the includes do appear.
So what I thought was just to separate this function. The first to simply load the maincontents and a second one for the sub-navigation to refresh only the sub-content area. I don't even understand how this script loads the include content dynamically since the link is the straight page2.php?page=sub1 link. All dynamic loaded content usually looks like "#index", without the ending ".php".
Some quick history:
I'm trying to get the best page structure. Deliver .php for non JavaScript user and then put some dynamic loading stuff over it. Always with the goal to keep the browser navigation and the browser links (for sharing) for each page in tact.
I'm not an jQuery expert. All I have learned so far was by trial and error and some logical thinking. But of course, I have a lack of fundamental knowledge in JavaScript.
So my "logical" question:
How can I tell the "nav" links to perform only their "$(window).bind"-Event and to tell the "subnav" links only to perfom their "$(window).bin"-event.
Is this the right thinking?
Since I've already been trying to solve it for nearly the last 18h, I'll appreciate any kind of help.
Thank you.
IMPORTANT:
With the first function I not just only load the maincontent but also I'm changing a div on the page with every link. So for any solution that might want to put it together in one, it won't work, cause they should do different things on different areas on the page. That's why I really need to call on the window.bind with each nav/subnav click.
Can anyone show me how?
Melros,
In your second function, you are binding to the event hashchange2, which is incorrect. Instead, you STILL want to bind to hashchange. Instead of:
$(window).bind('hashchange2', function() {
...
});
Try:
$(window).bind('hashchange', function() {
...
});
If you want to namespace your event subscriptions, you can suffix the ending of the event you are binding to with a period (.) and then the namespace:
$("#test").bind("click.namespace1", function() { });
$("#test").bind("click.namespace2", function() { });
Ok, it seems that you want to execute action A when a link inside .nav is clicked, and action B when a link inside .subnav is clicked.
You can just put these actions inside the event handlers. Furthermor, if .subnav is nested inside .nav, you have to restrict your selector:
// consider only direct children
$("ul.nav > li").delegate("a", "click", function() {
var href = $(this).attr("href");
if(window.location.hash !== href) {
Action A
window.location.hash = $(this).attr("href");
}
return false;
});
// consider only direct children
$("ul.subnav > li").delegate("a", "click", function() {
var href = $(this).attr("href");
if(window.location.hash !== href) {
Action B
window.location.hash = $(this).attr("href");
}
return false;
});
I don't think listening to the hashchange event will help you here, as this event is triggered in both cases and you cannot know which element was responsible (you probably can somehow, but why make it overly complicated?).
Here's by the way the solution I came to:
After understanding that the haschange-event doesn't have to do anything with it (as long as you don't want to make the subcontent bookmarkable too) I just added a new load function for the subcontent:
$(function(){
$("ul.linkbox li a").live('click', function (e) {
newLink = $(this).attr("href");
e.preventDefault();
$(".textbox").find(".subcontent").fadeTo(200,0, function() {
$(".textbox").load(newLink + " .subcontent" , function() {
$(".subcontent").fadeTo(200,1, function() {
});
});
$("#wrapper").css("height","auto");
$("ul.linkbox li a").removeClass("activesub");
$("ul.linkbox li a[href='"+newLink+"']").addClass("activesub");
});
});
});

Jquery .ClickOut Event

Hi everybody,
I have some issue with one of my project. I'm currently developing a toolbar for Google Chrome. The concept is that my extension insert by using a content script an iframe in every page i visit. Materialized in Red on my Printscreen.
After that i've created another iframe who appear when i click on the "Menu" Button. This iframe appear like a dropMenu. Materialized in orange in the printscreen.
Well now let me explain my problem :
When i click on the "dropMenuButton" i execute this code :
$( "#dM1").click( function() {
dropMenu('dropMenu1', $(this).position().left);
});
To be clear the function "dropMenu" will call my background page (by messaging exchange) to show or hide the dropMenu, in function if it's allready activated or not.
Here is the executed code by the "dropMenu function"
if(document.getElementById("dropMenu"))
{
$("#dropMenu").slideUp(800, function() {
$(this).remove();
});
}
else
{
var body = $('body'),
MenuURL = chrome.extension.getURL(dropMenuPage + ".html"),
iframe = $('<iframe id="dropMenu" scrolling="no" src="'+MenuURL+'">');
body.append(iframe);
$("#dropMenu").hide().slideDown(800);
// Shift the menu (Left)
$("#dropMenu").css({left: marginLeft+'px'});
}
So the event on dropMenuButton work perfectly but i want to provide some ameliorations like a .ClickOut event. What i want is that when somebody click outside the dropMenu (in orange) the menu will be hide.
I've tried a lot of things but nothing work...
Hope somebody will provide me some help !
Thanks in advance.
Edit (Injection) :
I've tried to inject the javascript like this :
var injectJs = $('<script type=text/javascript>' +
'$(document).click(function() {' +
'dropMenu("dropMenu1", 0);' +
'});');
body.append(injectJs);
injectJs = $('$("#dropMenu").click( function(e) {' +
'e.stopPropagation();' +
'});' +
'</script>');
body.append(injectJs);
But it didn't seems to inject on the page. It should have a problem somewhere...
Can't you just add a click event on the document? Then on the actual drop down menu (or any other events where you don't want to hide the drop down) prevent any clicks from bubbling up:
$(document).click(function(){
// hide drop down clicking anywhere on page:
$("#dropMenu").slideUp(800, function() {
$(this).remove();
});
});
$("#dropMenu").click( function(e) {
e.stopPropagation(); // prevent click on drop menu from removing the drop down.
});
It works great but like this :
$(document).click(function(){
// hide drop down clicking anywhere on page:
dropMenu('slideUp', 0);
});
$("#dM1").click( function(e) {
e.stopPropagation(); // prevent click on drop menu from removing the drop down.
dropMenu('dropMenu1', $(this).position().left);
});
Now i have to insert the similar code on the global page, someone have an idea how i can insert dynamically a js code ?

Categories