Jquery toggle activating on multiple elements instead of the element specified - javascript

alrighty Ive got what I hope is a rather easy question today for people knowledgeable in jquery. I have an toggle that activates on clicking a specific element, in this case I have targeted my logo image with an id of #logobutton. it works wonderfully however theres a problem, the animation also activates whenever I click on any and all other links on the page and even some random div boxed (like my nav bg). please note im very new to this javaScript jazz so I may be missing something you would consider quite obvious. thanks for the help!
here is the fiddle with all relevant code http://jsfiddle.net/tRf36/1/
jquery:
!--jquery script, must be above all jquery elements-->
<script type="text/javascript" src="jquery-1.11.0.min.js"></script>
<!--script for bg toggle-->
<script type="text/javascript">
$( document ).ready(function() {
$("#logobutton").click(function() {
$(".galbox").toggleClass("galbox-change");
});
});
</script>
<!--bg fade hide on load-->
<script>
$(document).ready(function(){
$("#gallerybox").fadeTo(3000, 0.00, function() {
$("#gallerybox").fadeTo(1000, 1.00);
});
});
</script>
hopefully someone can see if I have something targeted incorrectly or whatever is causing the issue of my generic rather than specific selection of clickable area to activate this bg animation.

My previous answer was completely off base, sorry for that. Looking at the jsfiddle that you posted it appears that you have the logo button like this <button ... /> the browser is then ignoring the /> and just wrapping everything in a button. So that means that both the gallery box and the nav bar are surrounded by the button that is activating the animation. Changing the button to be like this should fix it:
<button type="button" class="logo" id="logobutton" value=""></button>

close <button> tag properly using </button>
All elements below button are treated as children if you do not close properly.

Two aspects conspire to cause the effect:
You have nested your nav bar divs inside the #logobutton button.
Event bubbling causes events triggered on an embedded element to eventually reach the #logobutton button, being processed by the registered event handler.
A solution is to check for the triggering element of the click event:
$("#logobutton").click(function (eve) {
if ($(eve.target).attr("id") === "logobutton") {
$(".galbox").toggleClass("galbox-change");
}
});
You can test this modification with this fiddle.
You can learn more about event bubbling in particular and event processing in browsers following these links:
quirksmode (ppk)
MDN

Related

jQuery onclick load randomly working with firefox

So I have a few "boxes" with an onclick function:
<div class="box" onclick="load(1);return false;"></div>
<div class="box" onclick="load(2);return false;"></div>
The onclick functions trigger a function that reads the content of a few seperate .php files (example1.php and example2.php).
These files contain other boxes made with fieldset instead of a div.
function load(num){
$("#loadthis").load("example"+num+".php");
}
And the function above is changing the content of this div down here:
<div id="loadthis">Load my fieldset boxes</div>
So far everything works, until I click on the fieldset boxes.
The background color of the fieldset should change when I click it and the radio inside the fieldset should be selected too (because of css styling), but both of this does not happen. But I can still select the radio when clicking the radio (not the box).
I have tested it in IE and in Chrome, this code works there most of the time.
But in firefox I cannot select the fieldset box 50% of the time.
I tried to experiment with the .on( class but it gives me the same effect.
$('fieldset.type-a').children('.row').children('.box.col-4').on("click", load);
function load(){
var index = $('fieldset.type-a').children('.row').children('.box.col-4').index( this );
index+=1;
$("#loadthis").load("fs"+index+".php");
}
Okay so after some searching I found that there is already an onclick function in a different .js file that being called:
function handleStep2() {
$('.step-form-2 input[type=radio]').change(function () {
$(this).closest('fieldset').find('.box').removeClass('active');
$(this).closest('.box').addClass('active');
$(this).attr('checked', 'checked');
});
$('.step-form-2 .select-box .box').click(function () {
$(this).find('input[type=radio]').trigger('change');
});
}
I am now going to try to merge the codes and see if that gets rid of the bug with the active class not being activated on click.
SOLVED: I solved it by indeed merging both the codes to 1 click function. Thanks for all your help guys, But I still wonder if this could be done a different way?
Look into event delegation, and if you're using jQuery it's easy
look into the jQuery API for .on(
Also you want to make sure you're using unobtrusive JS, so pull that out of your HTML, put it in a .js file as an event listener and load the script after the DOM has loaded as the last thing before your closing </body> tag
It should be a delay about loading php files content.
Is it work when you click one of them even takes time?
Maybe you should ajax for loading php files. By the way you can send data to php files using GET or POST methods.
You can check this examples.
If your function is initalized in an IIFE, inline js can´t access this function.
It´s weird that you say this sometimes works..
IIFE is a wrapper function to create capsules, so the client can´t modify your script in runtime.
Looks like this:
(function(){
/* code */
}());
It would be much better to create js-events:
on('body', 'click', '.box', function(e) {
console.log(e.target); // this is the clicked list item
});
Hope it helps..

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

How to perform: onClick Javascript, hide a div with transition effect

This is a question that is related to a previous question of another member which can be found here.
This is the Javascript function to hide a div (which is an answer to the other member's question):
function hide(obj) {
var el = document.getElementById(obj);
el.style.display = 'none';
}
The HTML is:
<div id='hideme'>
Warning: These are new products
<a href='#' class='close_notification' title='Click to Close'>
<img src="images/close_icon.gif" width="6" height="6" alt="Close" onClick="hide('hideme')" />
</a>
</div>
My followup question to this is: how can I add a cool effect of transition? The result will be the div 'hideme' would close slowly. Is there a work around for this?
Thanks so much everyone! It would be highly appreciated!
Note: I'm a noob with Javascript. 0-0
$("#"+el).fadeOut(500);//el must be the id of the element
If you're using jQuery
function hide() {
$(this).parent().fadeOut();
}
As this is triggered by an event the 'this' variable will be set to the element from which it came, as you want the parent element to vanish when it's clicked this will do the trick
EDIT: For this to work you may have to play with your HTML and how many $(this).parent().parent()... you need but this would be the best way to go about it, then you don't need to pass the ID around
EDIT 2: So .parent() selects the element containing the selected element, so in this case $(this) refers to the button that was clicked as that's where the click event came from.
So $(this).parent() refers to the container element, in this case the a element and therefore the $(this).parent().parent() refers to the div element which you want to hide.
So you could give the image a class of 'closable' then do the following
$('.closable').click(function() {
$(this).parent().parent().fadeOut();
}
This means whenever you click something with the class closable it will go up the DOM tree two elements to (with .parent().parent()) and then fade it out.
This will allow you to remove the on click event from the image, you just need to put the handler above in the jQuery document.ready function which looks like:
$(document).ready(function() {
//Click function here
});
A popular choice for this would be JQuery UI's effect method.
With this, you can write some very simple Javascript to hide your div in a stylish manner, for example:
function hide(obj) {
$(obj).effect("scale");
}
EDIT:
Here's an example jsFiddle
Use jQuery to do transition effects:
$(function(){
$("a.close_notification").click(function(e){
e.preventDefault();
// stop other animations and hide, 500 milliseconds
// you can use the function fadeOut for that too
$("#hideme").stop().hide(500);
});
});

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 limit a click event applied to the <body> from executing on a jquery datatable in the body

I have animated datatables which slide in from the left when their hyperlink is clicked. And when the user is done reading the contents of the visible datatable, I applied the following code to allow the user to click anywhere else to park the table away and proceed with viewing. I used jQuery code for attaching the click event...
<script type="text/javascript" charset="utf-8">
$(document).ready( function () {$('.dtable').dataTable( {"sDom": 'rt',"sScrollY":"200px", "bPaginate":false, "bFilter":false} );**$('body').click(function() {parkDataTables();});})
</script>
Unfortunately, clicking on the datatable itself parks it. And I don't want that behavior. Maybe someone has an idea on how to block this click event from firing on the surface of the datatable...
Many thanks
Dennis
Instead of using body as the selector you could use
$('body').children().not('.dtable')
So you would get
<script type="text/javascript" charset="utf-8">
$(document).ready(
function () {
$('.dtable').dataTable( {"sDom": 'rt',"sScrollY":"200px", "bPaginate":false, "bFilter":false} );
$('body').children().not('.dtable').click(function() {
parkDataTables();
});})
</script>
You should do it with
$('.dtable').click(function(){return false;});
The problem is that when you click on the table, the event goes into the table first and then it propagates to the parents (and finally to the body, when the parkDataTables is catched).
You could also use stopPropagation instead ( http://api.jquery.com/event.stopPropagation/ ), because with the return false you also stop the default click behavior on the table.
$('.dtable').click(function(event){
event.stopPropagation();
});
Maybe you could check this page to see this last difference: http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/
Jquery propagates the function up through every parent. In order to stop the propagation, you must "return false;".
In your case, you want to try:
> $('body').click(function() { if $(this).hasClass('dtable'){return
> false;}) if $(this).hasClass('body'){park}
And give your body a class of 'body' to make it selectable.

Categories

Resources