click anywhere except a specified class - javascript

I need to show an alert if there is a click anywhere except on .m1wrap div.
Why this doesn't work? Alert appears even if I click on .m1wrap
$(document).on("click", function(e) {
if (e.target.class !== "m1wrap") {
alert ("323");
};
})

In e.target there is no property class (it returns undefined), you can use property e.target.className (Note it returns all classes from class attribute), however in jQuery there is method .hasClass .
Also you can use classList with .contains method e.target.classList.contains('m1wrap')
$(document).on('click', function (e) {
if (!$(e.target).hasClass('m1wrap')) {
console.log('not m1wrap');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="m1wrap">m1wrap</div>
<p>test</p>

You need to use className to address the class attribute.
So either use jQuery's hasClass() or vanilla JS className.
Note: This example using className is only checking if the class does not equal "m1wrap", rather than does not contain "m1wrap".
$(document).on("click", function(e) {
if (e.target.className !== "m1wrap") {
alert ("323");
};
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="m0wrap">m0wrap</div>
<div class="m1wrap">m1wrap</div>
<div class="m2wrap">m2wrap</div>

There is no class in e.target, only className is available.
Code snippets:
$(document).on("click", function (e) {
if (e.target.className !== "m1wrap") {
alert("323");
};
})
But the following code snippets is the best way if there is multiple class names for an element.
$(document).on("click", function (e) {
if (!$(e.target).hasClass('m1wrap')) {
alert("323");
};
})

Event.target returns Element, which has not class property.
So you can use className property or getAttribute() method to get Element's class name.
If you want to use jQuery API, you can use hasClass() method

Try this,
<div>
<div class="m1wrap">
Non Clickable area
</div>
Clickable area
Clickable area
Clickable areaClickable areaClickable
Clickable areaClickable
Clickable area
</div>
JS
$(('body')).on('click',function(e) {
if ($(e.target).hasClass('m1wrap')) {
return false;
}
alert("hello");
})
DEMO

Related

add and remove class on same button or element

I'm looking for a way to add and remove class on the same button. So far this is my work in progress. The concept is when I click on the menu button it shows the menu. When I tap on the menu button again. The menu hides
$(document).ready(function(){
$('button.toggle-portfolio').on('click', function(e){
$('.portfolio-contact-form-wrap').addClass('show');
});
});
To achieve this you can use .toggleClass() like so:
$(document).ready(function(){
$('button.toggle-portfolio').on('click', function(e){
$('.portfolio-contact-form-wrap').toggleClass('show');
});
});
JsFiddle example
toggleClass
Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the state argument.
This method takes one or more class names as its parameter. In the first version, if an element in the matched set of elements already has the class, then it is removed; if an element does not have the class, then it is added.
For more information about this function check here
Hope this helps!
You should use $(this) and toggleClass
$(document).ready(function(){
$('button.toggle-portfolio').on('click', function(e){
$(this).toggleClass('show');
});
});
which will add the class back to the specific element that was clicked.
http://api.jquery.com/toggleclass/
http://www.learningjquery.com/2007/08/what-is-this
Try this:
$(document).ready(function(){
$('button.toggle-portfolio').on('click', function(e){
$('.portfolio-contact-form-wrap').toggleClass('show');
});
});
DEMO
$('.toggle-portfolio').on('click', function(e) {
$('.portfolio-contact-form-wrap').toggleClass('show');
});
Try this way
You can use .add() method with .toggleClass():
$(document).ready(function() {
$('button.toggle-portfolio').on('click', function(e) {
$('.portfolio-contact-form-wrap').add(this).toggleClass('show');
});
});
.portfolio-contact-form-wrap {
color:blue;
}
.show {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="toggle-portfolio">Button</button>
<div class="portfolio-contact-form-wrap">
<h1>contact form</h1>
</div>
Use toggleClass('show')
It will add the class on one click and remove the class on the second click.
<script>
$(document).ready(function () {
$('button.toggle-portfolio').on('click', function (e) {
$('.portfolio-contact-form-wrap').toggleClass('show');
});
});
</script>

Change an ID upon click

I know how to change a class name with another class upon click, but not sure how to do so when using id instead.
Below is how the class is setup:
<script>
$(function(){
$(".collapseArrow").click(function(){
$(".collapseArrow").removeClass("collapseArrow")
$(this).addClass("collapseArrowUp")
return false;
})
})
</script>
The reason for that is that the class is already being used and i have to use the id to style it instead.
Plain Javascript approach:-
This approach takes advantage of the this keyword as follows...
HTML:
<div id="oldId" onclick="changeId(this)"></div>
JS:
function changeId(element) {
element.id = "someNewId";
}
or simply (in one line) as part of the HTML
<div id="oldId" onclick="this.id='someNewId';"></div>
jQuery approach:-
Use the attr() function as follows...
$(function(){
$("#oldId").click(function(){
$("#oldId").attr("id","newId");
return false;
});
});
EDIT: As requested, I will give a piece of code to toggle between 2 ids.
HTML:
<div id="firstId" onclick="toggleId(this)"></div>
JS:
function toggleId(element) {
if(element.id == "firstId") {
element.id = "secondId";
} else { //This will only execute when element.id == "secondId"
element.id = "firstId";
}
}
You can use the attr() function
<script>
$(function(){
$("#collapseArrow").click(function(){
$("#collapseArrow").attr('id',"collapseArrowUp");
return false;
});
});
</script>
Instead of changing the id, do it with multiple classes.
This could help you...
$(function(){
$(".collapseArrow").click(function(){
$(".collapseArrow").removeClass("up")
$(this).addClass("up")
return false;
})
})
You can use
$(this).attr("id"',"new id");
But i would use classes and add important to override existing css rules
Hope i helped
i have to use the id to style it instead.
I suggest you not to do this because in the dom structure ids have most preference against the class names. So this would be little difficult to override the styles which have been applied with the ids.
Instead i would recommend to use classes instead:
$(function() {
$(".collapseArrow").click(function() {
$(this).toggleClass("collapseArrow collapseArrowUp")
return false;
});
});
$(function() {
$(".collapseArrow").click(function() {
$(this).toggleClass("collapseArrow collapseArrowUp")
return false;
});
});
.collapseArrow::before {
content: "[-]"
}
.collapseArrowUp::before{
content: "[+]"
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 class='collapseArrow'></h1>
You should not change an id. If you need to use a different selector to select the same element, add another class to the element, e.g.
<span class="collapsArrow SomethingMeaningful"></span>
Then you just need to use a different selector method:
$( "span[class~='SomethingMeaningful']" )
.removeClass("collapseArrow")
.addClass("collapseArrowUp");
Then you can style the element with:
.SomethingMeaningful{
}

How to detect a click outside an element, but that element got children

I know this question might be repetitive as I have seen this solution: How do I detect a click outside an element?
I want to remove #main-element if I click outside the element, BUT, that element also has child elements inside. Meaning, if I click one of the child of #main-element, #main-element should not close
<div id="main-element">
<div class="test">1</div>
<div class="test">2</div>
<div class="test">3</div>
<div class="test">4</div>
</div>
I tried using this solution:
$('html').click(function(e){
if(e.target.id !== 'main-element') {
$("#main-element").removeClass("open").hide();
}
});
// For the trigger
$("#click-show").click(function(){
if($("#main-element").hasClass("open"))
{
$("#main-element").removeClass("open").hide();
}
else{
$("#main-element").addClass("open").show();
}
});
This might help:
DEMO
Use closest to loop through parents and classes to show/hide your element;
$('html').on('click', function(){
var mainElement = $('#main-element');
if($(this).closest(mainElement).length){
return;
}
mainElement.addClass('main-element-closed')
})
$('*').click(function(){
if($(this).has('#main-element') || $(this).parent().has('#main-element')){
// it will open here
}else{
//put your hide code
}
});
try to refer to function of jquery is HasClass('your child element class') with jquery.click(document)

alert individual attribute value [duplicate]

This question already has answers here:
Getting the ID of the element that fired an event
(24 answers)
Closed 9 years ago.
I want to identify each element by it's name attribute. Each element has the same class and will ultimately contain differing dynamic information.
For example I would want the following code to alert the individual element's name value:
html:
<p class="pexample" name="0">this is p #1</p>
<p class="pexample" name="1">this is p #2</p>
<p class="pexample" name="2">this is p #3</p>
jquery:
$('p').on('click', function() {
if ($('p').attr('name') !== undefined) {
alert($('p').attr('name'));
}
})
Here is a jsfiddle.. http://jsfiddle.net/XG7nd/1/
This code however only alerts the initial elements name value. Help is greatly appreciated.
This should do:
$('p').on('click', function() {
var name = $(this).attr('name');// `this` here refers to the current p you clicked on
if (name ) {
alert(name);
}
})
While doing $('p').attr('name') this will always give you the name of the first item in the collection.
Demo
Try this:
$(document).on('click','p', function() {
alert($(this).attr('name'));
});
DEMO
You want to use $(this)
$('p').on('click', function() {
if($(this).attr('name') !== 'undefined') {
alert($(this).attr('name'));
}
});
This is occurring because you are getting the name attribute for the first <p> on every click. You need to specify the one that the event originated from:
$('p').on('click', function() {
if ($(this).attr('name') !== undefined) {
alert($(this).attr('name'));
}
})
Note, jQuery selectors return an array of matching elements. You must use the this keyword to get a handle on the element in the current context.
FIDDLE
Explanation
You keep looking for the p element even on click, so it'll select the first one it finds.
What your code says:
When p is clicked:
Find a p element and alert its attribute.
What you really want:
When p is clicked:
alert the clicked element's attribute
Solution
Select the attribute of this, which is the clicked element.
JSFiddle
JavaScript
$('p').on('click', function() {
if ($(this).attr('name') !== undefined) {
alert($(this).attr('name'));
}
})
Read more about the this keyword.

If div is empty, remove it and change class of next div

Some generated output can be as follows:
<div class="fivecol"></div>
<div class="sevencol">content</div>
if the div.fivecol is empty, I want to remove it and change the div.sevencol to a div.twelvecol
$('.fivecol').each(function() {
if ($(this).html() ==''){
$(this).remove().next('sevencol').removeClass('sevencol').addClass('twelvecol');
}
});
doesn't do the trick. Any ideas?
$('.fivecol:empty + .sevencol').toggleClass('sevencol twelvecol')
.prev()
.remove();
DEMO: http://jsfiddle.net/JY9NN/
$('.fivecol').each(function(i, div) {
if (!div.html().trim()) {
div.remove().next('sevencol').removeClass('sevencol').addClass('twelvecol');
}
});
basically I just fixed some syntax errors, and changed the this reference to the proper argument call. Let me know how that works.
Best,
-Brian
Try this,
$(function () {
$('.fivecol').each(function() {
if ($(this).html() =='') {
$(this).remove();
$('.sevencol').each(function(){
$(this).attr('class','twelvecol');
});
}
});
});
We could use a couple fancy selector tricks:
$(".fivecol:empty + .sevencol").attr("class", function(){
return $(this).prev().remove(), "twelvecol";
});
As you can probably guess, .fivecol:empty attempts to find an empty element with the class fivecol. It then proceeds to grab the sibling element, using +, which has the class .sevencol.
Once we have our .sevencol element, we set out to change its class value to twelvecol. Since we're in this function, we know that .fivecol:empty was found, so we can safely remove it. Lastly, we simply return the new class value to be assigned in the place of sevencol.
Demo: http://jsfiddle.net/cLcVh/1/

Categories