Jquery event - how to select entire DIV excluding some inner area - javascript

Think of the following HTML code to apply Jquery:
HTML code:
<div id="outer_div">
<div id="inner_div_1"></div>
<div id="inner_div_2"></div>
<div id="inner_div_3"></div>
</div>
By default, the "outer_div" is hidden. It appears while clicked on a button using Jquery show() function.
I wanted to do the following: On click within anywhere of "outer_div" excluding the area within "inner_div_1" , the "outer_div" would again be hidden. I failed while tried the following codes. What should I amend?
Attempted Jquery 1:
$("#outer_div:not(#inner_div_1)").on("click",function(){
$("#outer_div").hide("slow");
});
Attempted Jquery 2:
$("#outer_div").not("#inner_div_1").on("click",function(){
$("#outer_div").hide("slow");
});
Your support would be highly appreciated.

You need to consider that a click in the inner div is also a click on the outter div. That being said, you just need to check the target and target parents :
$("#outer_div").on("click",function(e){
if(!$(e.target).closest('#inner_div_1').length) $("#outer_div").hide("slow");
});

You can use some of the data in the event
$("#outer_div").on("click",function(e){
if( // Fast check to see if this is the div
e.target.id !=='inner_div_1'
// We limit the 'closest()' code to the outer div. This adds children to the exclude
&& $(this).closest('#inner_div_1, #outer_div')[0].id=='outer_div'){
alert('good click');
}
});
This is a solution for your code now, this works perfect when not too many excluding objects. But no wildcard selectors, which is nice.
And a jsFiddle demo.
Other properties can be used to, like a class:
$("#outer_div").on("click",function(e){
if( e.target.className!=='even'
&& $(this).closest('.even, #outer_div')[0].id=='outer_div'){
alert('yay, clicked an odd');
}
});
I made 7 lines, gave the even ones a class 'even'.

Related

How to select some elements and append a div after them?

I've bene bursting my head for the last few hours. Here's the situation:
I have a website that has many divs, but many of them share classes (they are equal) but have some different texts. Example:
<div class="summary-title">
I Am That Girl</div>
<div class="summary-title">
I Am That Girl</div>
What I want to do is select each one of these divs and add a span whenever another div is hovered.
I mean, this is what I want to do: hover a div that's before the sumary-title div, a span with a class is appended inside the sumary-title div or out of it, whatever works.
That's what I got so far:
$('summary-title').each(function(index) {
var content = $(index).next().text();
$(index).append("<span class='hover-text'>"+content+"</span>");
});
But I get an error that $ is not defined, probably because it is a closure?
I have no idea what to do. The code seems horrible too — i need to do this quickly and I just can't do. Would anyone help me at least know what to do?
Thanks
append() is already an implicit iteration ( that loops through the set of elements in the jQuery collection.) and it's unnecessary to call .each() .
$('.summary-title').append(function() {
return "<span class='hover-text'>" + $('a', this).text() + "</span>";
});
Outside of making sure you have jQuery on your page and properly referring it, your code should go like:
$('.summary-title').each(function() {
var content = $(this).children('a:first').text();
$(this).append("<span class='hover-text'>"+content+"</span>");
});
Notice:
dot in class selector - $('.summary-title')
this instead of index - $(this)
children selector instead of next
Check demo - Fiddle.
To append this to a preceding element on hover use:
$(document).ready( function() {
$('.summary-title').hover( function() {
var content = $(this).children('a:first').text();
$(this).prev().append("<span class='hover-text'>"+content+"</span>");
});
});

Element not reacting to JQuery Click

I have added Elements using Jquery inside PHP after loading them from the database. Each button has two classes, one controlling the GUI and another controlling the Click for particular button. The code is as under
echo "<script type='text/javascript'>$('.main').append('<button class=b_ui b$index>Change</button>'); </script>";
Now if I check the classes from Inspect Element perspective of the browser, it shows 2 classes. But when I click on it and get class of element using this code
$('.b_ui').click(function()
{
cls = $(this).attr('class');
alert('no. '+cls);
}
It shows only first class (GUI) and not the other which I want to use for handling click.
Any help ?
Put quotes around the class attribute. <button class=\"b_ui b$index\">Change</button>
You should use "on" method:
$(document).on('click', '.b_ui', function() {
cls = $(this).attr('class');
alert('no. '+cls);
});
When adding elements dynamically to the DOM, they are not accessible by jQuery like an element which was there at page load. say you have this div:
<div id="div"></div>
and you add some content with jQuery so it now looks like this:
<div id="div"><span id="span"></span></div>
you cannot refer directly to the span using jQuery with $('span[id=span]'), you have to target a containing element then filter which contained element you want:
$('#id').on('click','span',function(){});

How to use not selector in jquery with multiple classes as one class

I have in my HTML div with one class tag and one with 2 classes that look like one class.
<body>
<div class="ad-container left">
<div class="ad-container">
<div class="mobile-ad larger">
<div class="mobile-ad">
</body>
Whats the proper way to use the not selector in jQuery to support all 4 div's and not ignore anything else in body.
I currently have
$('body:not(.ad-container,.ad-container.left,.mobile-ad.larger,.mobile-ad)')
It seems to work without any problems.
But something tells me I need to split the left and larger classes into seperate elements by comma.
Something like this
$('body:not(.ad-container,.left,.mobile-ad,.larger)')
Here is the full code:
$(function () {
$('body:not(.ad-container,.ad-container.left,.mobile-ad.larger,.mobile-ad)').on('selectstart', function (event) {
event.preventDefault();
});
});
It's used to disable the left double click selection but still be able to click on ads.
Which one should I use?
I ended up using
$('body :not(.ad-container, .mobile-ad)')

How do I select multiple classes incremented by 1 and their matching children?

I have multiple containers that I need to animate.
Basically: you click on class: box-n (e.g. box-1) and you slideToggle: box-child-n (e.g. box-child-1).
Instead of a click function for every box-n to toggle box-child-n, I want a simple line of code that matches box-n with its children class.
html:
<div class="box-1">Some clickable container</div>
<div class="box-child-1">This should toggle when box-1 is clicked</div>
<div class="box-2">Some clickable container</div>
<div class="box-child-2">This should toggle when box-2 is clicked</div>
Et cetera...
current jquery:
$('.box-1').click(function() { $('.box-child-1').slideToggle() });
$('.box-2').click(function() { $('.box-child-2').slideToggle() });
Sort of desired jquery (allInt function is made up.):
var $n = allInt();
$('.box-' + n).click(function() {
$('.box-child-' + _n).slidetoggle() // local variable to inter alia .box-1
})
I can't seem to think of any solution, so I am asking for help once again.
I appreciate every suggestion you folks give me!
Here's one way to do it that allows for the elements to have other classes besides the ones that you're using to pair them up:
$('div[class*="box-"]').click(function() {
var c = this.className.match(/\bbox-\d+\b/);
if (c)
$('div.' + c[0].replace(/-/, '-child-')).slideToggle();
});
Demo: http://jsfiddle.net/6xM47/
That is, use the [name*=value] attribute contains selector to find any divs with a class attribute that has "box-" in it somewhere. Then when clicked extract the actual class and check that it matches the "box-n" pattern - this allows for multiple (unrelated) classes on the element. If it does match, find the associated "box-child-n" element and toggle it.
Having said all that, I'd suggest structuring the markup more like this:
<div data-child="box-child-1">Some clickable container</div>
<div class="box-child-1">This should toggle when box-1 is clicked</div>
...because then the JS is simple and direct:
$('div[data-child]').click(function() {
$('div.' + $(this).attr('data-child')).slideToggle();
});
Demo: http://jsfiddle.net/6xM47/1/
To just answer your question, this will do the trick :
$("div[class^='box-']").click(function(){
$(this).parent().find('.' + $(this).attr('class').replace('-','-child-') ).slideToggle();
});
jsfiddle here.
Anyway i dont think you use a good approach (you may wrap child into parent div or use ids).

How can I use multiple Floating Help Dialogue by using 'class' instead of 'id'?

I need to use multiple floating help dialog boxes in a page. I have tried it by using 'display:block' and 'display:none' and used ID in javascript. I cannot use classes since I have multiple of them on the same page and if I use classes then all of them will be displayed/hide at the same time. However, as the number of help items are increasing in the page, I have to go back to the javascript and add more lines ...
for example:
$(document).ready(function() {
$("#help-icon1").click(function() {
$('#help-details1').css('display', 'block');
});
$("#help-icon2").click(function() {
$('#help-details2').css('display', 'block');
});
$("#help-icon3").click(function() {
$('#help-details3').css('display', 'block');
});
});
Each of them also have close icons and they should be disappeared if clicked on that close icon or clicked anywhere in the page. That means I have to write javascript functions 3 times for all the different close icons.
I tried to rely on jquery's "next" feature, but since there are many layers (div/p/span) in between the areas where the help icon is places and the help text, it becomes problamatic. Any idea or any better way to resolve this?
Thanks in advance.
I'm not quite sure I understand what you are looking for, but you can set up all the click handlers in one step, and have each one refer to itself in the handler:
jQuery(".help-icon").click(function() {
jQuery(this).css('display', 'block');
});
You can add additional class names to an element.
A div can be hidden by default, and a new class can be appended to it - to "overrule" the previous style (Hence the name Cascading Style Sheets)
<div class="hidden exception"></div>
If an element is clicked, you can append a new classname like so:
$('.target').addClass('newclass');
more info:
http://api.jquery.com/addClass/
I've not done it using JQuery but what you need is "unobtrusive javascript".
It does get done by using a class. Say you have images you all want highlighted:
<img src="pic1.png" onMouseover="this.src='hi_pic1.png';" />
so they all have the same behaviour. Give them a class:
<img src="pic1.png" class="hi" />
Then at load time, on in the script at the end of your page, yahoo-style, you write an initialisation to
- grab every element of the class
- add the event(s) you want
- set the event to use the appropriate data, e.g. by using this and by using systematic names like pic1 -> hi_pic1.
Hope this helps,
Charles
Have you tried the jQuery .each function?
EDIT: Like the following
$(".help-icon").each(function(idx, elm){
elm.click(function(){
...
})
});
If all of your help icons have the same class you can use jQuery's each function to loop through them, retrieve the associated id, replace "icon" with "detail" in the id (so #help-icon3 would become #help-detail3), and then use that to update the panel. Something like:
$(".help-icon").each(function() {
var detailsId = $(this).attr("id").replace("icon", "details");
$("#" + detailsId).css('display', 'block');
});
Let's just ASSUME that you need to use IDs for some unknown reason. Here's your answer to combine efforts:
$("#help-icon1").add("#help-icon2").add("#help-icon3").click(function() {
$(this).css('display', 'block');
});
Which equates to:
$("#help-icon1, #help-icon2, #help-icon3").click(function() {
$(this).css('display', 'block');
});
But really, you don't need to use unique IDs like this without some pretty good reasons.

Categories