mootools add an id - javascript

Is there a method like toggleClass() for and ID in mootools?

$("someid").toggleClass("selectedState"); // add or take away .selectedState to an element
but there is no native .toggleId, or am I not reading this question right. As suggested, use .set("id") or code your own function. if your objective here is to have, say:
formelement.getElement("input[type=submit]").toggleID("submitter");
it can go like so:
<div class="foo">foo</div>
...
Element.implement({
toggleID: function(id) {
return this.set("id", (this.get("id") == id) ? "" : id);
}
});
var el = document.getElement("div.foo");
el.toggleID("foo");
alert(el.get("id")); // foo
el.toggleID("foo");
alert(el.get("id")); // null

Use the Element.set(); method.
$('elementID').set('id', 'newId');
documentation: mootools docs

Related

jQuery if Element has an ID?

How would I select elements that have any ID? For example:
if ($(".parent a").hasId()) {
/* then do something here */
}
I, by no means, am a master at jQuery.
Like this:
var $aWithId = $('.parent a[id]');
Following OP's comment, test it like this:
if($aWithId.length) //or without using variable: if ($('.parent a[id]').length)
Will return all anchor tags inside elements with class parent which have an attribute ID specified
You can use jQuery's .is() function.
if ( $(".parent a").is("#idSelector") ) {
//Do stuff
}
It will return true if the parent anchor has #idSelector id.
You can do
document.getElementById(id) or
$(id).length > 0
You can using the following code:
if($(".parent a").attr('id')){
//do something
}
$(".parent a").each(function(i,e){
if($(e).attr('id')){
//do something and check
//if you want to break the each
//return false;
}
});
The same question is you can find here: how to check if div has id or not?
Number of .parent a elements that have an id attribute:
$('.parent a[id]').length
Simple way:
Fox example this is your html,
<div class='classname' id='your_id_name'>
</div>
Jquery code:
if($('.classname').prop('id')=='your_id_name')
{
//works your_id_name exist (true part)
}
else
{
//works your_id_name not exist (false part)
}
I seemed to have been able to solve it with:
if( $('your-selector-here').attr('id') === undefined){
console.log( 'has no ID' )
}
Pure js approach:
var elem = document.getElementsByClassName('parent');
alert(elem[0].hasAttribute('id'));
JsFiddle Demo
Simply use:
$(".parent a[id]");
You can do this:
if ($(".parent a[Id]").length > 0) {
/* then do something here */
}
You can use each() function to evalute all a tags and bind click to that specific element you clicked on. Then throw some logic with an if statement.
See fiddle here.
$('a').each(function() {
$(this).click(function() {
var el= $(this).attr('id');
if (el === 'notme') {
// do nothing or something else
} else {
$('p').toggle();
}
});
});

A smart toggle class in jQuery

I am trying to implement a script to set different class name on a specific element…
Let's suppose the dom looks like this:
<body class='pre-existing-class-name'>
If I make
smartToogle('body', 'new-class');
// the dom should look like this
// <body class='pre-existing-class-name new-class'>
smartToogle('body', 'new-class-2');
// the dom should look like this
// <body class='pre-existing-class-name new-class-2'>
I did the following code but it does not work:
var smartToogle = function (element, newClassName) {
var oldClassName;
var $element = $(element);
$element.addClass(newClassName);
if (oldClassName !== newClassName) {
$element.removeClass(oldClassName);
}
oldClassName = newClassName;
};
Requirements:
1) I am using query
2) I would like to pass just one class name, the new one.
Solution:
The following code works but I do not like it because it uses global variable.
Any hint to fix it?
function myToggle(newClassName) {
if (window.oldClassName) {
$('body').toggleClass(window.oldClassName);
}
window.oldClassName = newClassName;
$('body').toggleClass(newClassName);
}
You can use data attribute for the element, that is accessible using
$(element).data(attrib_name)
Just a small change is required in your method
function myToggle(newClassName) {
if (window.oldClassName) {
$('body').toggleClass(window.oldClassName);
}
window.oldClassName = newClassName;
$('body').toggleClass(newClassName);
}
can be replaced with
function myToggle(element, newClassName) {
if ($(element).data('oldClassName')) {
$(element).toggleClass($(element).data('oldClassName'));
}
$(element).data('oldClassName', newClassName)
$(element).toggleClass(newClassName);
}
Hope this solves it for you.
Update:
There is one thing you need to understand.
If you want two different behaviors you don't need 2 different classes for the change in behavior.
One is enough, because you can change the behavior based on weither the class is on or off.
Let's say I want my element to have a red hover event in one way.
And want it to have a blue hover event the other way with CSS.
Then this is the way to go:
$('#toggle').click(function(){
$('.normal').each(function(){
$(this).toggleClass('active');
});
});
JSFiddle Demo
Here we use a button to toggle all the divs and change their CSS behavior, looks easy now right?
However if you need to toggle Javascript/jQuery events as well this won't do. In that case you will need to use 3 other methods to manage this; .on(), .off(), and .hasClass().
$('#toggle').click(function(){
$('.normal').each(function(){
if($(this).hasClass('active')){
$(this).off('click');
} else {
$(this).on('click', function(){
alert('You are clicking on an active div.');
});
}
$(this).toggleClass('active');
});
});
JSFiddle Demo 2
As you can see we have added an if statement. If the element has the .active class we turn .off() the .click(). And if there isn't an active class we turn the .click() .on(). Under the if statement we always toggle the .active class. So this doesn't have to be placed inside the if statement.
I hope this clears everything up for you, good luck!
Old Answer:
It is better to use .toggleClass() here.
Use a first class on the element for the default properties and a second like .active for example for the interaction.
Also, using a .on('click', function(){}) bind will make you able to add interaction that will be bound instantly once the element is toggled.
Here's a fiddle: http://jsfiddle.net/NCwmF/2/
I little jQuery plugin for that. Removes the current smart class (if any) and adds the new smart class. If called without parameter className the current smart class gets only removed.
$.fn.smartToggle = function (className) {
var dataId = 'smartToggle';
return this.each(function () {
var $el = $(this);
$el
.removeClass($el.data(dataId) || '')
.addClass(className)
.data(dataId, className);
});
};
​use it like every other jQuery method:
$('body').smartToggle('myClass');
NEW, SIMPLER ANSWER
Works similar to before, with 2 additions: 1.) works if there is no class initially and 2.) works if other functions change the elements class in between calls. I also changed the function name so it doesn't interfere with jQuerys native toggleClass.
$.fn.fancyToggleClass = function(new_class) {
return this.each(function() {
// get the last class this function added (if exists) or false (if not)
var $this = $(this),
toggled_class = $this.data('toggled-class') || false;
// if we dont have an original class, then set it based on current class
if (toggled_class) {
$this.removeClass(toggled_class);
}
// add new class and store as data,
// which we check for next time function is called
$this.addClass(new_class).data('toggled-class', new_class);
// alert the class, just as a check to make sure everything worked!
// remove this for production, or switch to console.log
alert('element class: ' + $this.attr('class'));
});
}
updated fiddle: http://jsfiddle.net/facultymatt/xSvFC/3/
OLD ANSWER
I would suggest storing the original class in the elements data attribute. Then, your function can check if this data is set, and if so clear the elements class adding the original class from the elements data and also the new class you passed in the function.
If data is not set, the function will store the current class as data the first time it runs.
Check out this fiddle for a working example with comments: http://jsfiddle.net/facultymatt/xSvFC/
here is the code. It's a jquery function so it can be called on any element (and is chainable too!)
$.fn.toggleClass = function(new_class) {
return this.each(function() {
// cache selector for this
$this = $(this);
// get original class (if exists) or false (if not)
var original_class = $this.data('original-class') || false;
// if we dont have an original class, then set it based on current class
if (!original_class) {
original_class = $this.attr('class');
$this.data('original-class', original_class);
// we do have an original class, so we know user is now trying to add class
// here we clear the class, add the original class, and add the new class
} else {
// assign the original class, and new class,
// and a space to keep the classes from becoming one
$this.attr('class', original_class + ' ' + new_class);
}
// alert the class, just as a check to make sure everything worked!
// remove this for production, or switch to console.log
alert('element class: ' + $this.attr('class'));
});
}
Hope this helps!
To avoid a global variable you can use data attribute as #ankur writes. Here is a working solution for your problem:
function myToggle(element, newClassName) {
if (!$(element).data('baseclassname')) {
$(element).data('baseclassname', $(element).attr('class'));
}
$(element)
.attr('class', $(element).data('baseclassname'))
.addClass(newClassName);
}
Does this do your job?
var smartToogle = function (element, preExistingClassName, newClassName) {
$(element)[0].className = preExistingClassName + ' ' + newClassName;
};
Just use hasClass. But you'll have to tell the function what both classes are:
function smartToggle(element, class1, class2) {
var $element = $(element);
if ($element.hasClass(class1)) {
$element.removeClass(class1);
$element.addClass(class2);
}
else {
$element.removeClass(class2);
$element.addClass(class1);
}
}
$(function(){
var smartToggle = function (element, newClassName) {
var elementClasses = element.attr('class');
element.addClass(newClassName);
// check if there is more than one class on the element
if(elementClasses .indexOf(' ') >= 0){
var oldClassNames = elementClasses.split(" ");
if (oldClassNames[oldClassNames.length - 1] !== newClassName) {
element.removeClass(oldClassNames[oldClassNames.length - 1]);
}
}
};
smartToggle($('.test'), 'newclass');
smartToggle($('.test'), 'newclass2');
});
Demo - http://jsfiddle.net/Q9A8N/ (look at the console to see what it is doing on each pass)
That should do what you want but as #T.J. Crowder said it is rather fragile and assumes that the class you want to remove is the last one on the element.
As an answer to your question, I would go with ankur's answer
As a follow-up to Sem's answer, regarding the handling of jQuery events :
you can use the on function to handle any jquery event from a parent node, based on a live filter :
function myToggle(element, newClassName) {
if ($(element).data('oldClassName')) {
$(element).toggleClass($(element).data('oldClassName'));
}
$(element).data('oldClassName', newClassName);
$(element).toggleClass(newClassName);
}
//event delegation : 'on' is called on the $('.divContainer') node, but we handle
//clicks on '.divItm' items, depending on their current class
$('.divContainer')
.on('click', '.divItm.plain', function(){ myToggle( this, 'red' ); })
.on('click', '.divItm.red', function(){ myToggle( this, 'blue' ); })
.on('click', '.divItm.blue', function(){ myToggle( this, 'plain' ); });
//initialize each item with the 'plain' class
myToggle( $('.divItm'), 'plain' );
Here is the jsFiddle.
You will note that the function called each time you click on an item depends on its "live" class, and that you don't need to manually enable/disable click handlers each time an item changes class.
You can learn more details from the documentation page.
var smartToogle = function (element, newClass) {
var $element = $(element),
currentClass = $element.data('toggle-class');
if (currentClass != newClass) $element.data('toggle-class',newClass).removeClass(currentClass || '');
$element.toggleClass(newClass);
};
or the other variant:
$.fn.smartToogle = function (newClass) {
currentClass = this.data('toggle-class');
if (currentClass != newClass) this.data('toggle-class',newClass).removeClass(currentClass || '');
this.toggleClass(newClass);
};
In this implementation you'll have to keep the a reference to this instance of fancytoggle.
var fancytoggle = function(el, oldClass){
// create a function scope so we'll have a reference to oldClass
return function(newClass) {
// toggle the old class and the new class
$(el).toggleClass(oldClass+ ' ' + newClass);
// update the new class to be the old class
oldClass = newClass;
};
};
for your example the code would look something like.
var bodytoggle = fancytoggle('body', 'pre-existing-class-name');
bodytoggle('new-class');
// 'new-class' replaces 'pre-existing-class-name'
bodytoggle('new-class-2');
// 'new-class-2' replaces 'new-class'
to see it in action refer to http://jsfiddle.net/aaf2L/6/

Check if Attribute('id') Exists in jQuery

How can I check if an attribute Id exists in jQuery?
I searched around and found that this should work:
if ($(this).attr('id').attr('id'))
{
}
I still get this error: TypeError: Object gauge1 has no method 'attr'
This itself will work:
if($(this).attr("id"))
Check existing jsfiddle on the issue: http://jsfiddle.net/rwaldron/wVqvr/4/
Just try it the old way
if (this.id) {
//do something
}
You can use the is method and the Has Attribute Selector:
if ($(this).is('[id]')) {
}
if ($(this).attr('id')){
alert(id);
}
you could also just use the plain js object
if( this.id !== undefined && this.id.length > 0 ){
//todo: use id
}
HTML:
<div class="hey"></div>
<div class="you" id="woah"></div>
<div id="results"></div>​
jQuery:
var id = $('div.hey').attr('id');
if (id) {
// Have an id.
} else {
// Don't have an id.
}
A fiddle: http://jsfiddle.net/NEVYT/

how to check if div has id or not?

<div id="cardSlots">
<div class="ui-droppable" tabindex="-1" id="card1">one</div>
<div class="ui-droppable" tabindex="-1" id="card2">two</div>
<div class="ui-droppable" tabindex="-1">three</div>
<div class="ui-droppable" tabindex="-1">four</div>
</div>
<script>
$(".ui-droppable").each(function () {
if($(this).attr("id").length>0)
{
alert('here');
}
});
</script>
I am trying to loop through class but issue is i have card1 and card2 ids duplicate in that page. but above code seems to work but showing below error.
Uncaught Type Error: Cannot read property 'length' of undefined
I am trying to get ids from the loop which are there.
Use attribute selector selector[attribute] to get only the elements that have an ID
$('.myClass[id]') // Get .myClass elements that have ID attribute
In your case:
$('.ui-droppable[id]').each(function(){
alert( this.id );
});
jsFiddle demo
if(this.id) is all you need.
Why will this work?
If the element has an ID, the value will a non-empty string, which always evaluates to true.
If it does not have an ID, the value is an empty string which evaluates to false.
I am trying to get ids from the loop which are there.
To get a list of IDs, you can use .map like so:
var ids = $(".ui-droppable").map(function() {
return this.id ? this.id : null;
}).get();
or use the selector Roko suggests in his answer.
demo http://jsfiddle.net/QRv6d/13/
APi link: http://api.jquery.com/prop/
Please try this, this should help
code
$(".ui-droppable").each(function () {
if($(this).prop("id").length > 0)
{
alert('here');
}
});​
If there is no id attribute attr method will return undefined. Just write:
if($(this).attr("id"))
if(typeof $(this).attr("id") != 'undefined')
var $this = $(this);
if (typeof $this.attr("id") != "undefined" && $this.attr("id").length > 0) {
...
}
If you're going to use $(this) more than once, it's advised to find it once, and put the resulting jQuery object in a local variable.

How to add class to element only if it already does not have it?

How to add a class to an element only if it already does not have it? Say we don't know if the element has class="desired_class ... but we want to make sure it has.
Also, you can use classList property and it's add() method:
var element = document.getElementById('myElement');
element.classList.add('myClass');
The class name will be added only if the element does not have it.
More about classList:
https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
try this
var elem = $('selector');
if(!elem.hasClass('desired_class')){
elem.addClass('desired_class');
}
I wrote a JavaScript-only function that checks if the class exists before adding it to the element. (You can always use classList as mentioned here, but support for that starts with IE10.)
function addClass(name, element) {
var classesString;
classesString = element.className || "";
if (classesString.indexOf(name) === -1) {
element.className += " " + name;
}
}
var element = document.getElementById('some-element');
addClass("on", element); // Adds the class 'on'
addClass("on", element); // Ignored
addClass("on", element); // Ignored
document.write('Element classes: ' + element.className);
<div id="some-element"></div>
In plain javascript check class existence by using below code. Here I'm checking el (element) has tempClass or not
var el = document.getElementById("div1");
...
if (el.classList.contains("tempClass")){
return true;
}
if ($('element').hasClass('some_class')) {
$('element').addClass('class_name');
}
Are you sure you want to do it with JQuery only? You can do it with simple JavaScript
document.getElementById("elementId").getAttribute("class")
will give you null if the class attribute is not present.
if (!$("your_element").hasClass("desired_class")) {
$("your_element").addClass("desired_class");
}
An updated answer to this question is using toggleClass
$( "element" ).toggleClass( "className" );
http://api.jquery.com/toggleclass/

Categories

Resources