Best way to dynamically add and remove style on elements - javascript

I am using mouseenter and mouseleave events on some elements to change their appearance. I am able to do so using either of the following two strategies:
$(this).css('someProperty','someValue') to add and then $(this).removeAttr('style') to remove
$(this).addClass('someClass') to add and then $(this).removeClass('someClass') to remove
What is the best way to do so?

Definitely option 2. Styles should be defined in the stylesheet.
There's also toggleClass, which removes the class if it's there, but adds it if it's missing.
Note: toggleClass also lets you pass in a Boolean as the second argument, telling it whether to add or remove it (regardless of whether it currently has that class applied), so:
$(this).toggleClass('active', true);
is exactly equivalent to:
$(this).addClass('active');
This is very handy when you have a Boolean in your code already. So instead of this:
if (isUserActive()) {
$(this).addClass('active');
} else {
$(this).addClass('active');
}
You could just do this:
$(this).toggleClass('active', isUserActive());

Option 2 if you must do it in JavaScript, but for modern browsers you may be able to achieve what you're after entirely in CSS using :hover pseudo-classes.

I'd strongly recommend addClass()/removeClass(), since you can add, remove and change a whole swathe of properties with minimal jQuery.
Whereas the css() method requires you, or rather the script, to keep track of what should be changed to reflect the aesthetic change(s) to convey programmatic interaction, coupling that with the attr() method and removing the style attribute will remove all styles, even those you want the element to retain, which requires you to reassign those properties.
So, basically, option 2 is efficient, and option 1 creates unnecessary work.
There is, of course, always toggleClass(), which can promote further efficiency.

Unless you need to dynamically generate any of the CSS property values you're better of separating the styles from the javascript. So use classes instead of direct css styles.

.addClass and .removeClass is the best way because you can style you changes with your CSS ...so after a while you can easily redesign your site.

Second one is best because normally style will is common for different elements, it will generic and adding removing is good compared with adding attribute one by one.
$(this).addClass('someClass') to add and then $(this).removeClass('someClass') to remove

If you are calling this function in more than one element I suggest you to use the second one. If you needed to change the appearance again later, then you have to edit only within the css class, not in all elements

Related

Best practice in finding a DOM element

I want to toggle(hide/show) an element when a button is being pressed. I have two ways as to implement this:
Find the element according to its class name, e.g $('.my-content')
Find the element according to its relevant DOM position towards the button, e.g. $('#my-button').parent().next().next().next()
However, none of the above seems to me very reliable since in case someone changes the HTML code, the above approaches should not work. Is there something more reliable I am missing?
If it's a specific element, supply it with an Id value and use that
to find it.
If it's a TYPE of element, use a class name.
Other than that, there's no real conventions. Just try and make sure that somebody reading your code understands what is going on.
A very good practice is to decouple HTML, CSS and JS.
When binding javascript to DOM elements you should use javascript selectors.
Basically classes with some custom prefix (like js-) which will be used only for javascript purposes (not css style).
So whenever the DOM tree structure or the CSS class names are changed, you can still have your working JS selector
HTML
<div class="my-content js-toggle-element"></div>
JS
$('.js-toggle-element')
CSS
.my-content{ ... }
Plus, using Javascript Selectors:
makes HTML highly readable: you can easily find out what will happen to that element with that js class
allows you to easily apply/disapply that behaviour also to other elements in the future, simply by adding/removing that class in your HTML and without affecting CSS at all
<div class="my-content js-toggle-element"></div>
...
<div class="another-content-to-toggle js-toggle-element"></div>
Using jQuery will be much easiest way. Like this -
$( ".target" ).toggle();
The matched elements will be revealed or hidden immediately, with no animation, by changing the CSS display property. If the element is initially displayed, it will be hidden; if hidden, it will be shown.
Reference - jQuery Toggle
If the class or the position of the element in DOM is changing then you can try
selecting it with the inner text
$("button:contains('buttontextgoeshere')")

jquery allow only one of a group of classes on an element?

I have an element that gets a number of classes added to it + removed from it dynamically using jQuery. I'd like to ensure that I have only one of a set of classes on the element at a given time.
For example, I could have the .blue_element class that defines a font color, background color, border color, etc., and I wouldn't want that on the element at the same time as a .red_element class or a .yellow_element class, but I wouldn't mind it being on at the same time as a .small_element class or .big_element class.
Current method:
$('#target_element').removeClass('yellow_element').removeClass('red_element').addClass('blue_element')
This works fine but seems like it creates a risk for error, e.g. if I add a .purple_element class but forget to modify my removal code.
I'm doing this on a larger scale than in my example and may be adding and removing classes quite frequently, so I'd expect to make some boneheaded mistakes if I do it this way. Is there a more efficient way to do this?
Instead of using jQuery use native mathod
document.getElementById("target_element").className = 'blue_element';
Above code will remove all classes and keep/add only 'blue_element';

css :not() selector with selector list incoming

I have many css selectors and many selector exception, so I use :not to leave them out...
example (just some selectors I don't need):
[class*="-dashboard-"]:not([class$="-binding"]), [class*="-dashboard "]:not([class$="-binding"]), [class$="-dashboard"]:not([class$="-binding"])
But what I instead would prefer is:
([class*="-dashboard-"],[class*="-dashboard "],[class$="-dashboard"]):not([class*="-binding-"],[class*="-binding "],[class$="-binding"])
or something else, that ist shorter than the working one and easier to edit and not so repetitive...
My problem is that I have that selectors in big list. The user is allowed to add/remove lists so I have to dynamically change the selectors and exceptions.
Does anybody have an idea to short that one???
Usually, the way my CSS looks is with increasing specificity. A very generic rule sets a whole lot of defaults, and then something that positively matches one of those rules you gave us overrides that style with something else.
For instance, you could set a higher-priority rule for anything ending in "-binding" that makes elements invisible, or whatever you intend for them. In simple terms, to calculate a CSS rule's priority:
Add 100 for each ID selector
Add 10 for each class selector
Add 1 for each other selector
I think you'd do well by having more classes in your elements that are easily selected, ie anything that adds a lolwtf-dashboard class should also add a dashboard class that's easily CSS-selected.

Which is better practice for adding a class using jQuery?

$("#" + parentElementId + " label").attr("class", "disabled")
VS
$('#radiolabel').addClass('disabled');
Which are the pros and cons?
Thanks
The two are not the same. Using attr will replace the whole attribute. addClass will add the class to the existing classes.
As the name suggests addClass is made for this specific purpose, so I'd use that.
Here are some advantages of the two ways to do this:
addClass("disabled") Pros:
If you have other classes on your object, addClass() will preserve those while adding a new class. I pretty much always want to preserve the ability to use other classes for CSS styling reasons or common selector reasons so addClass() makes it possible to add the disabled class without disturbing other classes on the same object for other reasons.
The code reads a little more self-explanatory since the name addClass() tells someone reading the code exactly what it's doing.
addClass() automatically manages separators between class names so there is no extra accumulation of separators when you have multiple class names which can occur if you just get the current classname and add onto it yourself with string manipulation.
attr("class") = "disabled" Pros:
If you only ever want one class name on the object, this one statement insures that you will have only one class name.
A direct assignment of the one class can be faster than addClass() which has to examine what's there first and add a class to the pre-existing classes which jQuery does with a regex match. Max speed would actually be with element.className = "disabled" (no jQuery at all).
I'd go for addClass, it's easier to read, and if your editor supports code completion, also faster to type.
You better go for the addClass() you will save time and writting, and gain more efficiency.

How to get original browser set input colors back after changing them with jQuery().css()?

Problem with jQuery:
After changing the border and background color of some input fields in a form that fail the validation i don't know how to get the previous, original colors back as i don't pre-style the inputs but use the browser settings instead. how to handle this?
thanks in advance,
clubnite
This will remove the color from the style element styles, causing the stylesheet to resume control.
$(sel).css('color', '')
Note that this will not restore the color to a value that was explicitly set before. To do that, you'd have to cache the prior values.
Set the value of your modified attributes to inherit
What you should be doing is not changing the CSS attributes, but adding a css class to the element. When the validation fails, remove that CSS class.
I would use a CSS class instead of setting individual properties with jQuery. That way, you can just add and remove the class to apply or remove the style. It's simpler, probably faster, and lets you keep all your style information together in one place. Adding a class also makes it easier to find all the fields that have errors with jQuery selector.
If, for whatever reason, you really want to use .css(), you can remove the properties by setting them to an empty string. For example, if you added a border, you would remove it with
$(selector).css("border", "");

Categories

Resources