Check for the class in an element - javascript

If there is an element with the class myclass in the #main element, I want to alert ok but in my example it always shows no, how can fix this?
Demo: http://jsfiddle.net/mF2K6/1/
<form>
<div id="main">
<div class="myclass"></div>
</div>
<button>Click Me</button>
</form>
$('button').live('click', function (e) {
e.preventDefault();
//var copy_html = $('#main').clone();
//if ($('#main').hasClass('myclass')) {
if ($('#main').is('.myclass')) {
alert('ok');
} else {
alert('no');
}
})

To check sub-elements for myclass, use this:
if ($('#main').find('.myclass').length != 0)
or this:
if ($('#main .myclass').length != 0)

Your <div id="main"> does not have myclass class, only one of its children has it.
You can check the latter with the following code:
if ($("#main .myclass").length > 0) {
alert('ok');
} else {
alert('no');
}

Something like this should help:
$("button").click(function () {
window.alert(isClassPresent() ? "Yes" : "No");
});
function isClassPresent() {
return $("#main .myclass").length > 0;
}

this will work fine:jsfiddle
var main=$("#main");
$("button").click(function(){
if(!!main.find(".myclass").length){
alert("ok");
}else{
alert("no");
};
});
[0]is method can't to compare different doms!
[1]why must use live?
[2]cache main(jQuery Object) is more efficient.select only ones.

Related

jQuery do something when element is shown

I want my code to execute when an element is shown.
$('.test').on('click', function(){
$('.sub-slider').toggle();
$('.sub-slider').on('show', function(){
console.log("hi");
});
});
Try this:
var visible = $("#ele"/*select the element*/).is(":visible");
console.log(visible);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ele"></div>
You can delete the div to test it.
Try like this.Wrap the function inside the toggle.And check the element is display property is block then pass your stuff
$('.test').on('click', function() {
$('.sub-slider').toggle(function() {
if ($(this).css('display') == 'block') {
console.log('showing')
}
});
});
Example
$('.test').on('click', function() {
$('.sub-slider').toggle(function() {
if ($(this).css('display') == 'block') {
console.log('show')
}
else{
console.log('hide')
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="test">click</button>
<p class="sub-slider">text</p>

javascript sort with data handlers issue

sorry if this is a stupid question but I'm a bit of a javascript novice and I'm trying to learn better programming instead of "cheating" and writing out each event type individually.
I can't seem to get this to run. The user clicks on a link at the top of the page with a data attribute with an event types ID number in it (data-event-type="1", etc). It should hide any events without that id number. JS and HTML is below.
JS fiddle with it all
http://jsfiddle.net/96r9jqp6/
HTML
<div class="sort">
All
Trainer
Conference
</div>
<div class="events-container">
<div class="eventsys-event-wrapper" data-event-type="1">
event 1 info here
</div>
<div class="eventsys-event-wrapper" data-event-type="2">
event 2 info here
</div>
<div class="eventsys-event-wrapper" data-event-type="1">
event 3 info here
</div>
<div class="eventsys-event-wrapper" data-event-type="2">
event 4 info here
</div>
</div>
Javascript
<script src="text/javascript">
$(document).ready(function(){
$('.eventSort').click(function(){
if (event.preventDefault) event.preventDefault();
else event.returnValue = false;
var thisEventSort = $(this).attr("data-event-sort");
if (thisEventSort = "0"){
$('.eventsys-event-wrapper').show('fast');
return;
} else {
$('.eventsys-event-wrapper').each(function(){
var thisEventType = $(this).attr("data-event-type");
if (thisEventType = thisEventSort) {
$(this).show('fast');
} else {
$(this).hide('fast');
}
});
}
});
});
</script>
if (thisEventSort = "0")
needs to be
if (thisEventSort === "0")
and same for
if (thisEventType = thisEventSort)
needs to be
if (thisEventType === thisEventSort)
Something like this
$('.eventSort').click(function(e){
e.preventDefault();
var thisEventSort = $(this).data("event-sort");
$('.eventsys-event-wrapper').hide().filter(function() {
return thisEventSort === 0 ? true : ($(this).data('event-type') == thisEventSort);
}).show('fast');
});
FIDDLE
You didnt pass event also... so your if there is not needed...
and use .data("event-sort") for this...
$(document).ready(function(){
$('.eventSort').click(function(event){
event.preventDefault();
var thisEventSort = $(this).data("event-sort");
if (thisEventSort == "0"){
$('.eventsys-event-wrapper').show('fast');
return;
} else {
$('.eventsys-event-wrapper').each(function(){
var thisEventType = $(this).attr("data-event-type");
if (thisEventType == thisEventSort) {
$(this).show('fast');
} else {
$(this).hide('fast');
}
});
}
});
});
I've updated your jsfiddle here
http://jsfiddle.net/96r9jqp6/5/
the most import piece is your use of the "=" operator
you need to use triple equal to test for equality instead of just one.
also when using data-* attributes, you should use the jquery .data() function to retrieve its values
$(document).ready(function(){
$('.eventSort').click(function(){
if (event.preventDefault) event.preventDefault();
else event.returnValue = false;
var thisEventSort = $(this).data("event-sort");
console.log(thisEventSort);
if (thisEventSort === 0){
$('.eventsys-event-wrapper').show('fast');
return;
} else {
$('.eventsys-event-wrapper').each(function(){
var thisEventType = $(this).data("event-type");
if (thisEventType === thisEventSort) {
$(this).show('fast');
} else {
$(this).hide('fast');
}
});
}
});
});

Check for empty attribute jquery

I'm trying to check an element for an empty attribute, but can't seem to get things to work.
Here's my html code:
<div class="item">
<div class="itemBtn" style="visibility:hidden;">
</div>
<div class="itemText" itemtype="loader">
</div>
</div>
<div class="item">
<div class="itemBtn">
</div>
<div class="itemText" itemtype="">
</div>
</div>
Here's a jquery hover function that essentially just turns on the button. I was trying to build upon it by saying 'if theres no itemtype, dont turn it on'
inner.find(".item").hover(function () {
if (inner.find(".item-text[itemtype='']")) {
$(this).children(".itemBtn").css("visibility", "hidden");
} else {
$(this).children(".itemBtn").css("visibility", "visible");
}
}, function () {
$(this).children(".itemBtn").css("visibility", "hidden");
});
UPDATE:
I ended up solving this by doing the following:
inner.find(".item").hover(function () {
if ($(this).find("div[itemtype='']").length) {
$(this).children(".itemBtn").css("visibility", "hidden");
} else {
$(this).children(".itemBtn").css("visibility", "visible");
}
}, function () {
$(this).children(".itemBtn").css("visibility", "hidden");
});
it's just simple example
var attr = $(this).attr('title');
if (typeof attr !== typeof undefined && attr !== false) {
//do some thing
}
Use .attr like this with a conditional:
var attr = $(this).attr('title');
if (!attr) {
// Do something
}
Or you can make it more concise by checking the attribute in the conditional like this:
if (!$(this).attr('title')) {
// Do something
}
if (! $('.item-text').attr('itemtype') ) {
alert("Nothing in itemtype");
} else {
alert("Not empty");
}
Very simple, just check to see if the attribute exists or not using attr(), like so:
if (!$(this).attr('title')) {
alert('Exists!');
}

Detect user selection within html element

How can I detect if a user selection (highlighting with mouse) is within/a child of a certain element?
Example:
<div id="parent">
sdfsdf
<div id="container">
some
<span>content</span>
</div>
sdfsd
</div>
pseudo code:
if window.getSelection().getRangeAt(0) is a child of #container
return true;
else
return false;
Using jQuery on() event handler
$(function() {
$("#container > * ").on("click",
function(event){
return true;
});
});​
Edit: http://jsfiddle.net/9DMaG/1/
<div id="parent">outside
<div id="container">
outside
<span>first_span_clickMe</span>
<span>second_span_clickMe</span>
</div>
outside</div>
$(function() {
$("#container > span").on("click", function(){
$('body').append("<br/>child clicked");
});
});​
​
Ok I managed to solve this in a "dirty" way. The code could use improvement but it did the job for me and I am lazy to change it now. Basically I loop through the object of the selection checking if at some point it reaches an element with the specified class.
var inArticle = false;
// The class you want to check:
var parentClass = "g-body";
function checkParent(e){
if(e.parentElement && e.parentElement != $('body')){
if ($(e).hasClass(parentClass)) {
inArticle = true;
return true;
}else{
checkParent(e.parentElement);
}
}else{
return false;
}
}
$(document).on('mouseup', function(){
// Check if there is a selection
if(window.getSelection().type != "None"){
// Check if the selection is collapsed
if (!window.getSelection().getRangeAt(0).collapsed) {
inArticle = false;
// Check if selection has parent
if (window.getSelection().getRangeAt(0).commonAncestorContainer.parentElement) {
// Pass the parent for checking
checkParent(window.getSelection().getRangeAt(0).commonAncestorContainer.parentElement);
};
if (inArticle === true) {
// If in element do something
alert("You have selected something in the target element");
}
};
}
});
JSFiddle

How can I change the class of an element with jQuery>

I have a JavaScript function that looks like this:
function UpdateFilterView() {
if (_extraFilterExists) {
if ($('#F_ShowF').val() == 1) {
$('#extraFilterDropDownButton').attr('class', "showhideExtra_up");
$('#extraFilterDropDownButton').css("display", "block");
if ($('#divCategoryFilter').css("display") == 'none') {
$('#divCategoryFilter').show('slow');
}
return;
} else {
if ($('#divCategoryFilter').css("display") == 'block') {
$('#divCategoryFilter').hide('slow');
}
$('#extraFilterDropDownButton').css("display", "block");
$('#extraFilterDropDownButton').attr('class', "showhideExtra_down");
return;
}
} else {
if ($('#divCategoryFilter').css("display") != 'none') {
$('#divCategoryFilter').hide('fast');
}
$('#extraFilterDropDownButton').css("display", "none");
}
}
This will be triggered by the following code (from within the $(document).ready(function () {}):
$('#extraFilterDropDownButton').click(function() {
if ($('#F_ShowF').val() == 1) {
$('#F_ShowF').val(0);
} else {
$('#F_ShowF').val(1);
}
UpdateFilterView();
});
The HTML for this is easy:
<div id="divCategoryFilter">...</div>
<div style="clear:both;"></div>
<div id="extraFilterDropDownButton" class="showhideExtra_down"> </div>
I have two problems with this:
When the panel is hidden and we press the div button (extraFilterDropDownButton) the upper left part of the page will flicker and then the panel will be animated down.
When the panel is shown and we press the div button the panel will hide('slow'), but the button will not change to the correct class even when we set it in the UpdateFilterView script?
The correct class will be set on the button when hovering it, this is set with the following code:
$("#extraFilterDropDownButton").hover(function() {
if ($('#divCategoryFilter').css("display") == 'block') {
$(this).attr('class', 'showhideExtra_up_hover');
} else {
$(this).attr('class', 'showhideExtra_down_hover');
}
},
function() {
if ($('#divCategoryFilter').css("display") == 'block') {
$(this).attr('class', 'showhideExtra_up');
} else {
$(this).attr('class', 'showhideExtra_down');
}
});
To set a class completely, instead of adding one or removing one, use this:
$(this).attr("class","newclass");
Advantage of this is that you'll remove any class that might be set in there and reset it to how you like. At least this worked for me in one situation.
Use jQuery's
$(this).addClass('showhideExtra_up_hover');
and
$(this).addClass('showhideExtra_down_hover');
<script>
$(document).ready(function(){
$('button').attr('class','btn btn-primary');
}); </script>
I like to write a small plugin to make things cleaner:
$.fn.setClass = function(classes) {
this.attr('class', classes);
return this;
};
That way you can simply do
$('button').setClass('btn btn-primary');

Categories

Resources