overlay conflict with query live search - javascript

On a onepager website i've a livesearch implemented which works as a overlay. The results are shown like this:
<div style="display: block;" id="LSResult">
<ul id="LSShadow">
<li><a owl="sl23" slide="5" rel="sl23#6" class="clk_s">Team</a></li>
<li><a owl="sl22" slide="9" rel="sl22#10" class="clk_s">Trust Services</a></li>
</ul>
The click-function looks like that:
$('.clk_s').click(function() {
alert("click");
$('.search_ov').fadeOut();
})
Unfortunately, if i click on a result-link nothing happens. I don't know, but there must be some conflicts with the overlay/livesearch output - because if i testing without overlay, everything works.
Can somebody help me or know whats wrong?
thanks + best regards
thomas

The problem is that you are binding to the click event on elements that don't exist yet. Since the event is bound on page load, but the search function renders the .clk_s elements way after that, they will never trigger the event handler.
One way to solve this is to bind the handler on a parent instead, say <body> for example, and fire the handler when the event was triggered on a child that matches your selector. That way you have bound only one event handler, and it will trigger on any .clk_s no matter when they were added to the document.
Changing your snippet to this should do the trick:
$('body').on('click', '.clk_s', function () {
alert("click");
$('.search_ov').fadeOut();
});
For more info on jQuery's on() function: http://api.jquery.com/on/

Related

How to trigger an event on a group of elements?

I have a listener on a group of elements:
$('a.menu__link').on('click',function() {alert('function was triggered');});
One element of which is:
<a class="menu__link menu__link--submenu Main" id="Events" href="#">Events</a>
I want to manually trigger a click on the element. Using Chrome dev tools, the event handler is:
a#Events.menu__link.menu__link--submenu.Main
However, the following code does not trigger the listener:
$('a#Events.menu__link.menu__link--submenu.Main').trigger('click');
I have tried every variation that I can think of, but I cannot find the correct reference to trigger the alert function.
What am I doing wrong?
You can use instead click instead of trigger like this to trigger a click :
$('#div').click();
Read more about click here
Here is a JsFiddle
I encased the trigger in a $(document).ready(function()) and that fixed it.
Kudos to Blazemonger for implying that it was a timing issue.
<script>$(document).ready(function() {
$('#Events').trigger('click');
$('#PastSeminars').addClass('menu__link--current');
});</script></body></html>
The lesson? Just because it is the last thing on the page, when in doubt, use document.ready.
Chrome blocks the click event from being programmatically fired. I'd come up with a new solution such as just calling the needed function wherever you need to trigger it.
You can read more about it here: https://teamtreehouse.com/community/why-does-my-onclick-event-not-fire-on-chrome

JQuery - Event do not fire for element under some other element

I am facing a situation where I want to handle click event of li that is present under another element with class optWrapper. Most of these mark-up is generated due to third party javascript libraries. So, markup is something like
<div class="optWrapper multiple open">
<ul class="options">
<li data-val="7"><span><i></i></span><label>Critical Illness</label></li>
<li data-val="25"><span><i></i></span><label>Critical Illness Insurance</label></li>
<li data-val="3"><span><i></i></span><label>Critical Illness Silver</label></li>
</ul>
</div>
and my jQuery code is
$(".optWrapper li").click(function () {
alert();
});
I can't find why this event is not getting called. Please help.
Edit 1
I am guessing this behavior is due to these element are loaded after jquery has downloaded in browser, is it that? if yes, than how could I tackle with it?
Edit 2
These element are dynamically generated after dropdownlist's select event.
The answer of onsubject is correct. Saying to use .on instead of .click.
After jQuery 1.7 the preferred method is .on()
Addition on the answer of #onsubject , because his answer won't work, on dynamically created
".optWrapper li"
Instead of the actual element, use the body or its parent element.
$('body').on('click', '.optWrapper li', function() {
//do something
}
These element are dynamically generated after dropdownlist's select event.
Oops, your event listener attached before creation.
As javascript event bubbles up target to document, you can handle that event by listening parent of them. See Direct and delegated events section
Attach event listener to the parent which don't generate dynamically.
$('#someparent').on("click","li.your_target",function(){
alert();
});
Put your jquery code in $(document).ready(function (){});
It will work fine.
You can use .on instead of .click
$(".optWrapper li").on("click", function () {
alert();
});
See a working version here:
http://codepen.io/ramiror/pen/zGeXPO
Try this solution:
$(document).ready(function(){
$(".optWrapper ul li").live('click', function(e){
alert("eureka");
});
});

Keydown event not removed from document and not registering on div element

NOTICE: The cause of the problem has been found, read the comments to the first answer.
I have a dropdown list of things, that is hidden until the user invokes it.
It's something like this:
<div>
<button></button>
<ul>
<li></li>
....
<li></li>
</ul>
</div>
The basic idea:
The list becomes visible when the user presses the button shown in the code above.
I need to make the list able to be navigated by keyboard,
i.e. if the user presses up or down while the list is open, the appropriate li will be selected (as if the mouse was hovering over it instead)
The event listener responsible for giving this functionality to the list should be attached when the list becomes visible and be removed when the list becomes hidden again.
Something like what Bitbucket does for the dropdown lists, but even simpler.
The issue:
I tried to attach an event listener to the ul and then on the div element, when the former had no effect, to no avail.
The code is this
ON SHOW
this.<ul or div element here>.addEventListener('keydown', this.keyboardNavigation.bind(this));
ON HIDE
this.<ul or div element here>.removeEventListener('keydown', this.keyboardNavigation.bind(this));
and the callback is like so
function keyboardNavigation(e) {
console.log('foo');
}
NOTE: "this" is an object to which the div and the ul are both properties of, and the callback function is actually a method of that object.
QUESTION 1:
Why is the keydown event not working when I attach it to either the ul itself or the parent div?
Anyway, since these did not work, I decided to attach the listener to the document.
ON SHOW
document.addEventListener('keydown', this.keyboardNavigation.bind(this));
ON HIDE
document.removeEventListener('keydown', this.keyboardNavigation.bind(this));
Same callback.
Now, while this works, I noticed that the event listener is not removed from the document.
I later noticed that another keydown event listener I had attached to the document for another task, is also not removed when that task is done, while it should.
QUESTION 2:
Why are the event listeners not removed? I cannot understand what I am doing wrong, I am removing the exact same callback on the exact same event as were those that were added.
Any help will be much appreciated.
NOTE:
I have tried doing it with jQuery's .on() and .off() instead, as suggested here, although I do not want to use jQuery, yet same thing is happening.
My thoughts:
1 Is it because the DIV or UL isn't getting the keyboard events because the don't have focus? Whereas the document is always getting the bubbled events?
To test this, click in the DIV/UL and type and see if the keyboard events get triggered then.
I think binding to the document - if you want the user to be able to just start typing after clicking - is the right thing to do here.
2 Is this because you are not removing the same handler you created? You should retain a reference to the handler you create with the first bind call and pass this reference in to the remove call - otherwise you're creating another (different) handler and asking to remove that.
E.g.:
var f = this.keyboardNavigation.bind(this);
document.addEventListener('keydown', f);
document.removeEventListener('keydown', f);

Jquery global events and dynamically added content

I'm trying to trigger my own custom events as global events, so that anything on my page can listen to them and react, however, for dynamically added content it's not working. See my fiddle at: http://jsfiddle.net/6TMkG/8/
As far as I understand, the event is triggered for any element in the page that jQuery knows has a handler for it, and it seems it doesn't trigger the event for the li's even though they do have a handler.
Anyone know how to get around this behaviour?
try this
$("#b2").click(function() {
//$.event.trigger("randomEvent");
$('li').trigger('randomEvent');
});
If you want global event, then you could bind the event handler on document, and trigger it on any element in the document.
$(document).on('randomEvent', callback);
$('ul').click(function() {
$(this).trigger("randomEvent");
});
Sorry I completely missed that.. I did not see the first part of your question.. Custom events.. Looks like you are associating the randomEvent but you are not triggering that event when that is associated with it..
Make sure you add the trigger Event in the Document.Ready function so that the evnet handler is associated with as and when the element is available.

Append element problem

I am creating some elements and appending it, and its working fine but when I want to call any function or want to call any jquery that not work, but when i put that elements directly instead of appending then it works properly. In all to say that appending element does not call any function or anything.
JQUERY CODE:
var cart_content = jQuery($.create('li', {}, [])).append($.create('span',{}, [av_title]),$.create('img', {"src":"images/delete_icon.png", "class":"cart_content", "alt":"delete", "title":"Delete"}, []));
$(".advertise_cart").append(cart_content);
$(".cart_content").click(function(){ alert("Hello"); });
<ul class="advertise_cart" id="advertise_cart_id">
<li>
<span>Inner Content 1</span>
<img src="images/delete_icon.png" class="cart_content" alt="delete" title="Delete"> <!------ On clicking on this will show alert box, but on clicking on appended element will not call alert box or anything ----->
</li>
</ul>
Thanks in advance
The problem you're experiencing is the result of the elements not being present in the DOM when the events are bound. To work around this, you can use delegate() or live():
$('body').delegate('.cart_content','click',
function(){
alert('hello');
});
JS Fiddle demo.
References:
live().
delegate().
Do not use .click function.
Use live function it work for newly added element in DOM
like this :
$(".cart_content").live(function(){ alert("Hello"); });
Using the live function to handle your event might help.
The only thing I'd add is that the live function means that the handler will continue to be applied to content that matches the selector at any point in the future (until and unless you call unbind). That is probably what you want here. If it isn't, you could write could that would add the click handler after a brief delay (say, 1.5 seconds). Or to be a little more sure, you could write code that would check for the presence of .cart_content every 100 milliseconds until it's found, and then add the click handler. So this approach would add the click handler only once. If something caused another .cart_content were added later, the click handler would not automatically be added.

Categories

Resources