How to capture 'body' and inside 'body' events in a page[Jquery] - javascript

what my current Code do :
i have this HTML
<li>
<span>Logged in as</span>
<a class="user" href="#"><?php echo $this->loggedas ?></a>
<a id="loginarrow" href="javascript: void(0);"></a>
</li>
this is my JS for above loginarrow id
$("#loginarrow").click(function() {
$("#logindrop").toggle("slow");
return false;
});
its working great but i can close it by clicking it again.
i dont want so i want that if its open and i click on background so it must close.
for that i did so
$("#loginarrow,body").click(function() {
$("#logindrop").toggle("slow");
return false;
});
now its working cool,But Got another problem.
1 = i have many other html elements in Page (Body) in which there are other events to call.so in this case whenever i click other elements in my page so its Toggling my this div loginarrow.
i want the same functionality but not on my other elements only on background.
Any Hint

close it only when it visible.
$("body").click(function() {
if ($("#logindrop").is(":visible"))
$("#logindrop").hide("slow");
});

A fundamental design principle for good browser performance is to only capture events while you're interested in them.
So put your .click() handler on the #loginarrow element, but in that handler register a one-off event handler on the body that will close it again. Something like (untested):
$('#loginarrow').click(function() {
$('#logindrop').show('slow');
$('body').one('click', function() {
$('#logindrop').hide('slow');
});
return false;
});
This will ensure that you're not unnecessarily intercepting every click on the body except when you really need to.
​See http://jsfiddle.net/alnitak/vPHaj/

Related

jQuery function prevents add / remove class on click

I'm trying to have a div get a new class (which makes it expand) when being clicked, and get it back to the old class (which makes it close) when clicking on a cancel link inside that div.
<div class="new-discussion small">
<a class="cancel">Cancel</a>
</div>
<script>
$('.new-discussion.small').click(function() {
$(this).addClass("expand").removeClass("small");
});
$('a.cancel').click(function() {
$('.new-discussion.expand').addClass("small").removeClass("expand");
});
</script>
Now, adding the expand class works flawlessly, but closing the panel after clicking on the cancel link only works when I remove this code:
$('.new-discussion.small').click(function() {
$(this).addClass("expand").removeClass("small");
});
So I guess this must be preventing the second function to work, but I really can't figure out why.
Any ideas?
Thanks!
Try this
$('a.cancel').click(function() {
$('.new-discussion.expand').addClass("small").removeClass("expand");
return false;
});
Reason may be your click event is getting propagated to parent which is also listening to click event.
Since your a element is inside the .new-discussion element, when you click on the a, it also fires the click event on the parent element because the event is bubbling up.
To fix it, you can stop the propagation of the event by calling e.stopPropagation();. That will prevent any parent handlers to be executed.
$('a.cancel').click(function(e) {
e.stopPropagation();
$('.new-discussion.expand').addClass("small").removeClass("expand");
});
Since the link is inside the <div>, it's using both click methods at once. It might help to do a check to see if the container is already open before proceeding:
<script>
$('.new-discussion.small').click(function() {
if ($(this).hasClass("small")) {
$(this).addClass("expand").removeClass("small");
}
});
$('a.cancel').click(function() {
$(this).parent('.expand').addClass("small").removeClass("expand");
});
</script>

Prevent icon inside disabled button from triggering click?

Trying to figure out proper way to make a click event not fire on the icon of a disabled link. The problem is when you click the Icon, it triggers the click event. I need the selector to include child objects(I think) so that clicking them triggers the event whenever the link is enabled, but it needs to exclude the children when the parent is disabled.
Links get disabled attribute set dynamically AFTER page load. That's why I'm using .on
Demo here:(New link, forgot to set link to disabled)
http://jsfiddle.net/f5Ytj/9/
<div class="container">
<div class="hero-unit">
<h1>Bootstrap jsFiddle Skeleton</h1>
<p>Fork this fiddle to test your Bootstrap stuff.</p>
<p>
<a class="btn" disabled>
<i class="icon-file"></i>
Test
</a>
</p>
</div>
</diV>​
$('.btn').on('click', ':not([disabled])', function () { alert("test"); });​
Update:
I feel like I'm not using .on right, because it doesn't take the $('.btn') into account, only searching child events. So I find myself doing things like $('someParentElement').on or $('body').on, one being more difficult to maintain because it assumes the elements appear in a certain context(someone moves the link and now the javascript breaks) and the second method I think is inefficient.
Here is a second example that works properly in both enabled/disabled scenarios, but I feel like having to first select the parent element is really bad, because the event will break if someone rearranges the page layout:
http://jsfiddle.net/f5Ytj/32/
Don't use event delegation if you only want to listen for clicks on the .btn element itself:
$('.btn').on('click', function() {
if (!this.hasAttribute("disabled"))
alert("test");
});​
If you'd use event delegation, the button would need to be the matching element:
$(someParent).on('click', '.btn:not([disabled])', function(e) {
alert('test!!');
});​
Demo
Or use a true button, which can really be disabled:
<button class="btn" [disabled]><span class="file-icon" /> Test</button>
Demo, disabled.
Here, no click event will fire at all when disabled, because it's a proper form element instead of a simple anchor. Just use
$('.btn').on('click', function() {
if (!this.disabled) // check actually not needed
this.diabled = true;
var that = this;
// async action:
setTimeout(function() {
that.disabled = false;
}, 1000);
});​
.on('click', ':not([disabled])'
^ This means that, since the icon is a child of the button ".btn", and it is not disabled, the function will execute.
Either disable the icon, also, or apply the event listener only to the <a> tag that is your button, or use e.stopPropagation();
I would suggest using e.stopPropagation();, this should prevent the icon from responding to the click.
That doesn't seem to work for me ^
Disabling the icon, however, does.
I would prefer to add the event using delegation here as you are trying to base the event based on the attributes of the element.
You can add a check condition to see if you want to run the code or not.
$('.container').on('click', '.btn', function() {
if( $(this).attr('disabled') !== 'disabled'){
alert('test!!');
}
});​
Check Fiddle
You're not using the selector properly.
$('.btn').not('[disabled]').on('click', function () {
alert("test");
});​
See it live here.
Edit:
$('.container').on('click', '.btn:not([disabled])', function () {
alert("test");
});​
I think what you need is:
e.stopPropagation();
See: http://api.jquery.com/event.stopPropagation/
Basically something like the following should work
$('.icon-file').on('click', function(event){event.stopPropagation();});
You may want to add some logic to only stop bubbling the event when the button ist disabled.
Update:
not sure, but this selector should work:
$('.btn:disabled .icon-file')

How to attach a onclick callback to a div but not on a link inside the div?

Html
<div class='item_container'>
[...bunch of links and pictures...]
<a class='item_owner'>John Doe</a>
</div>
Javascript
/**
Bind the onclick only if you hover on the item since we got a lot
of items and several events and plugins to setup on them.
*/
$('.item_container').live('mouseenter', function(e){
$this = $(this);
if (!$this.data('isSetup')) {
$this.click(function(e){
// do magic
return false;
});
[... a lot of other stuff]
$this.data({'isSetup': true});
}
});
Of course when I click anywhere in the div, it performs 'do magic'. Thanks to return false, if I click on any link in the div, it still performs 'do magic' and doesn't change the page, which is the expected behavior.
But there is one link that is suppose to actually change the page, the owner link. Trouble is, with my current set up, I prevent it from working.
You need to stop the propagation of the event from the links to the parent .item_container.
Add this block to the code:
$('.item_container a.item_owner').live('click', function(e){
e.stopPropagation();
});

How to tell JavaScript to do nothing?

I have a small chunk of code, like this:
$("div.footerMenu li").click(
function () {
$("div.onScreen").hide();
$(this).children("div.onScreen").fadeIn('fast');
},function(){
$("div.onScreen").hide();
});//click
And when I click on <li> the div .onScreen shows nicely, but when i click on this div, that just showed up the functions is hiding in and showing again, but I don't want it to execute this function again. So my question is: How can I somehow "detach/exclude/hide" this div from Javascript?
update:
The thing is that with this method and with others with .one() the rest of menu is not working. There is the site with the problem here . I want this div that shows up stay there, when I click on it, but when I click on their items <li> I want to other div's (submenus) to show up (warning - big images on that site).
The html looks like this:
<div class="footerMenu"> <ul> <li>HOME<div class="onScreen"><div style="padding:50px;"><img src="fillTxt.png"></div></div></li> <li>PLENER<div class="onScreen"> <div style="padding:50px;"><img src="fillTxt2.png"></div></div> </li> <li>STUDIO<div class="onScreen"> <div style="padding:50px;"><img src="fillTxt.png"></div></div> </li> <li>INNE<div class="onScreen"> <div style="padding:50px;"><img src="fillTxt2.png"></div></div> </li> </ul> </div>
The simple solution is:
$('div.footerMenu li').unbind('click');
But should you have multiple click handlers on the selector, you may want to only remove one at a time. The way to do that is to store a reference to the function being passed:
function hideItem()
{
...code...
//unbind the click event
$(this).unbind('click', hideItem);
}
$('div.footerMenu li').click(hideItem);
If you want to handle an event only once, you can use the one() method:
$("div.footerMenu li").one("click", function() {
$("div.onScreen").hide();
$(this).children("div.onScreen").fadeIn("fast");
});
You can use .one():
$("div.footerMenu li").one('click', function(){
things_to_happen_only_once();
// unbinding happens automatically
});

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