How to check already given class and add another one - javascript

recently I wrote one few lines of js in order to check the DOM structure and add "in" class in case user clicked on link. Now I need to use has property but I dont know how its used. Here is code:
$(document).on('click', '.collapse-all > a', function () {
var $collapseList = $(this).closest('#main-content').find('.collapse-list'),
$container = $collapseList.find('.collapse').removeAttr('style'),
$collapsed = $collapseList.find('.mehr-pfeil');
if ($container.filter('.in').length > 0) {
$container.removeClass('in');
} else {
$container.addClass('in');
}
});
$(function () {
$('.collapse-all > a').click();
});
// here is my try to check the DOM and add another class on <a> element
$(function () {
$container.hasClass('in') {
if ($container.filter('.in').length > 0) {
$collapsed.addClass('mehr-pfeil-active');
} else {
$collapsed.removeClass('mehr-pfeil-active');
}
}
});
So right now everything worked but when I tried to check if js has gave in class to .collapse then my code breaks. Can anyone tell me where I've made mistake

hasClass() returns a bool so your function may check something like this
if($container.hasClass('in')) {
...
}
As noted by TheBlueAussie, your $container is also not in the scope of your ready function.
A quick fix would be to global the variable like so
var $container;
$(document).on('click', '.collapse-all > a', function () {
var $collapseList = $(this).closest('#main-content').find('.collapse-list'),
$collapsed = $collapseList.find('.mehr-pfeil');
$container = $collapseList.find('.collapse').removeAttr('style');
...
}

There are 2 problems in your code
1,$container is not in the scope of your class checking function.
2, The way you used hasClass method is wrong
It will return true or false. So you can check it inside an if condition.
var $collapseList = $(this).closest('#main-content').find('.collapse-list');
$container = $collapseList.find('.collapse');
if ($container.hasClass('in')) {
$collapsed.addClass('mehr-pfeil-active');
} else {
$collapsed.removeClass('mehr-pfeil-active');
}

take a look at
.hasClass() to check if element has a class.
you can use it in a if and than addClass
if($('.class').hasClass('className'))
{
$('.class').addClass('xy');
//or
$('.class').removeClass('className');
//and so on
//.class could be #id as well
}

You should move the hasClass statement to a condition start since this method returns a boolean (true/false) value:
// here is my try to check the DOM and add another class on <a> element
$(function () {
if ($container.hasClass('in')) {
if ($container.filter('.in').length > 0) {
$collapsed.addClass('mehr-pfeil-active');
} else {
$collapsed.removeClass('mehr-pfeil-active');
}
}
});
You should also declare the $container variable inside this function or move its initialization to be a global one.

try this
$container.hasClass('in');
or if you want to toggle class
$container.toggleClass('in')

Related

Confused with calling JQuery custom function

I have html like so
<span rel='comm' val='12'>click</span>
<span rel='comm' val='82'>click</span>
and I am using JQuery to do this
$('span[rel*=comm]').cust();
and the custom function is as such
$.fn.cust = function () {
$(this).click(function(e) {
alert($(this).val());
});
}
The value of this is 12 even when I click on 2nd span which should give me 82
Any help would be appreciated.
You'll need to return a seperate function for each element in the collection, normally done with return this.each ...
$.fn.cust = function () {
return this.each(function() {
$(this).click(function(e){
alert($(this).val());
});
});
}
And value is not a valid attribute for a span element.
This should work better:
$.fn.cust = function () {
$(this).click(function (e) {
alert($(this).attr('val'));
});
}
span does not have value.
http://jsfiddle.net/dREj6/
Also if you want to make your method chainable you should return an jQuery instance:
$.fn.cust = function () {
return $(this).click(function (e) {
alert($(this).attr('val'));
});
}
$('span[rel*=comm]').cust().css('color', 'red');
http://jsfiddle.net/dREj6/1/
rel are for links (anchor element) - use class
use data attribute instead of custom attributes
http://jsbin.com/ogenev/1/edit
<span class='comm' data-val='12'>click</span>
<span class='comm' data-val='82'>click</span>
$.fn.cust = function(){
$(this).click(function(){
alert(this.dataset.val);
});
};
$('.comm').cust();
It works if you use .attr('val')
$.fn.cust = function () {
$(this).click(function(e){
alert($(this).attr('val'));
});
}
$('span[rel*=comm]').cust();
http://jsfiddle.net/fW7FT/
.val() is for input since they're the only one accepting the val attribute officialy
The call $('span[rel*=comm]') returns a JQuery wrapper for all spans matching the selector - the two ones you have in your example are picked both.
Now inside the definition of cust, $(this) refers to the wrapped array, which causes your issue. Use
$(this).each( function() {
$(this).click (...
});
Inisde each $(this) will point to each separate span element in the selection, so they will have the click handler individually attached and working as you expect.
You can achieve what you're looking for with this:
HTML:
<span rel='comm' val='12'>click</span>
<span rel='comm' val='82'>click</span>
JS:
var cust = function(source) {
alert($(source).attr('val'));
}
$('span[rel*=comm]').click(function(e) {
cust(this);
});
The JSFiddle working: http://jsfiddle.net/ejquB/

Get element under a selector with jquery

I have a selector where I get the first element like that:
$("#MyControl")[0]
Is it possible to get the element with a function other than accessing the elements like a array?
What I want to do with that is to pass this element to a function with .call() to defines the context.
Here is an example:
$(document).ready(function () {
$(document).on("change", "#MyControl", setActivityControlsState);
});
setActivityControlsState: function () {
var selector = "#automaticActivityCreation";
if ($(selector).length > 0) {
if ($.isNumeric(this.value) && this.value > 0)
$(selector).show();
else
$(selector).hide();
}
}
referenceFormOnSuccess: function (data) {
setActivityControlsState.call($("#MyControl")[0]);
}
As you can see in the refreshFormOnSuccess function, I must defines 'this' with $("#MyControl")[0].
I just want to know if is there a better way to do that.
Note that I don't want to access the value of my control with something like $(this).val()
May I suggest a small re-structuring that mitigates that need:
$(document).ready(function () {
$(document).on("change", "#MyControl", setActivityControlsState);
});
setActivityControlsState: function () {
// cache jquery object instead of just the selector
// for better memory management
var automaticActivityCreation = $("#automaticActivityCreation");
if (automaticActivityCreation.length > 0) {
if ($.isNumeric(this.value) && this.value > 0)
automaticActivityCreation.show();
else
automaticActivityCreation.hide();
}
}
referenceFormOnSuccess: function (data) {
// fire the change event which will tap
// the listener you set up in .ready
$("#MyControl").trigger('change');
}
but if you really want to get the object with jquery you do have some options:
// jQuery select #MyControl and get as dom element with array
$("#MyControl")[0]
// jQuery select #MyControl and get as dom element with .get
$("#MyControl").get(0)
but because you are using an element with an ID and you can only use a single ID at a time you really don't need jquery for this
document.getElementById('MyControl')
or
referenceFormOnSuccess: function (data) {
setActivityControlsState.call(document.getElementById('MyControl'));
}

empty div not getting recognised in javascript

i am creating an empty div in the javascript DOM. but when i call some function on it, for example,
var hover = document.createElement("div");
hover.className = "hover";
overlay.appendChild(hover);
hover.onClick = alert("hi");
the onClick function isn't working. Instead it displays an alert as soon as it reaches the div creation part of the script. What am i doing wrong?
Try addEventHandler & attachEvent to attach event to an element :
if (hover.addEventListener)
{
// addEventHandler Sample :
hover.addEventListener('click',function () {
alert("hi");
},false);
}
else if (hover.attachEvent)
{
// attachEvent sample :
hover.attachEvent('onclick',function () {
alert("hi");
});
}
else
{
hover.onclick = function () { alert("hi"); };
}
You need to put the onclick in a function, something like this:
hover.onclick = function() {
alert('hi!');
}
The property name is "onclick" not "onClick". JavaScript is case sensitive.
It also takes a function. The return value of alert(someString) is not a function.

Toggle State Incorrect in jQuery

I am using jQuery to show / hide lists, but it takes two clicks on a link instead of just one to show the list. Any help?
jQuery.showList = function(object) {
object.toggle(function(){
object.html("▾");
object.siblings("ul.utlist").show("fast");
}, function(){
object.html("▸");
object.siblings("ul.utlist").hide("fast");
});
}
$(document).ready(function() {
$("#page").click(function (e){
e.preventDefault();
var target = $(e.target);
var class = target.attr("class");
if(class == "list")
$.showList(target);
});
});
It's probably because toggle thinks the object is already visible, and executes the 'hide' clause.
edit:
Eh.. quite circular logic; how else would a user be able to click on it :-)
PS. You changed the logic from is-object-visible? to is-list-visible? in your own reply.
Not sure if this will fix everything but stop using reserved keywords.
Change variable class to something like c. And Change object variable to at least obj.
Doing the following worked well
jQuery.showList = function(obj) {
var list = obj.siblings("ul.utlist");
if(list.is(":visible")){
obj.html("▸");
list.hide("fast");
} else {
obj.html("▾");
list.show("fast");
}
}

addClass function not worked using JQuery

I have the following code:
function showAccessRequests_click() {
var buttonValue = $("#showAccessRequests").val();
if (buttonValue == "Show") {
$(".hideAccessRequest").removeClass("hideAccessRequest");
$("#showAccessRequests").val("Hide");
}
else {
$(".hideAccessRequest").addClass("hideAccessRequest");
$("#showAccessRequests").val("Show");
}
}
This script removes a class fine but it does not want to add the class. Can you see any issues with this code?
When you add hideAccessRequest class to the element, you search for it by the existence of that class.. if you are adding it, that class won't already be applied and thus you won't match any elements.
$(".hideAccessRequest") doesn't exist. you need to use id, I guess. And you might want to look at toggleClass.
you'd need an identifier for the classes you want to toggle ex:"accessRequest"... try this.
function showAccessRequests_click() {
var buttonValue = $("#showAccessRequests").val();
if (buttonValue == "Show") {
$(".accessRequest").removeClass("hideAccessRequest");
$("#showAccessRequests").val("Hide");
}
else {
$(".accessRequest").addClass("hideAccessRequest");
$("#showAccessRequests").val("Show");
}
}
classes are space-delimited, so if you want them hidden by default...
<div class="accessRequest hideAccessRequest">...</div>

Categories