Short Intro of jQuery Inbuilt Methods for Handling CSS

Published September 26, 2017 by saurav.roy.

Manipulating the UI style or CSS at runtime is a very common project. With plain JavaScript, adding and removing CSS classes or inline stylings of the matched element can be tricky. Luckily, jQuery has some inbuilt methods to make this whole process effortless! The methods are .addClass(), .removeClass(), .hasClass(), .toggleClass() and .css(). The names of these methods are self-explanatory and give you some insight into their functionality. In this short post, we’ll look at each of these methods in action.

.addClass()

The .addClass() method simply adds the class to any element. It doesn’t replace a class, it simply appends. To add a CSS class to any element,

$("#elm").addClass("myClass");

This method adds a class attribute to the selected element. You can also add multiple CSS classes in one go. Just separate the class names with a space. Like,

$("#elm").addClass("myClass myClass2");

.removeClass()

The .removeClass() method removes a single class, multiple classes, or all classes from each element in the set of matched elements. Like,

$("#elm").removeClass("myClass");

If you don’t supply any class name, then all the CSS classes applied to the matched element will be removed. Like,

$("#elm").removeClass();

.hasClass()

If you want to check if a CSS class is assigned to an element or not, use the hasClass() method. This will return true or false. Consider the following HTML,

<div id="elm" class="dummy"></div>

The following jQuery code will return true:

$("#elm").hasClass("dummy");

This is quite useful in cases where, based on certain conditions, you need to take further actions.

.toggleClass()

The .toggleClass() method is a combination of the .addClass() and .removeClass() methods. This method takes one or more class names as its parameter. It first checks 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. Consider the following HTML,

<div id="elm" class="dummy"></div>

The following jQuery code attaches toggleClass() method to the div element.

$("#elm").toggleClass("dummy2");

When this code runs for the first time, it adds dummy2 class to the div element because the original element didn’t have it. So the HTML becomes,

<div id="elm" class="dummy dummy2"></div>

When the same jQuery code runs for the second time, it removes dummy2 CSS class from the div element and the HTML reverts back to the original,

<div id="elm" class="dummy"></div>

.css()

All the above method deals with the class attribute, but the .css() method is used for inline style. It adds and removes style attributes for the selected element. For example, to change the background color to red,

$("#elm").css("background-color", "red");

This will add the style attribute to the element. Like,

<div id="elm" style="background-color:red;"></div>

Using this method, you can also set multiple CSS properties in one call. Like,

$("#elm").css({
 "background-color", "red",
 "color", "black"
 });

Or get the value of any CSS property. Like,

var backColor = $("#elm").css("background-color");

To remove any inline CSS property, simply pass an empty string. Like,

$("#elm").css("background-color", "");

Bonus tip: If you want to completely remove the inline style attribute, then use the removeAttr() method,

$("#elm").removeAttr("style");

Conclusion

This post provides a brief insight into various inbuilt methods available in jQuery to play around with CSS or inline element styling. These methods can add, remove or toggle the CSS classes or inline style. Using these methods can save a lot of development time and creates a clean code. Definitely worthy of your jQuery toolkit!

The Pixelize jQuery Plugin

Published March 22, 2014 by saurav.roy.

I am unabashedly and unreasonably fond of pixel art. It evokes a nostalgia for a simpler time (tinted generously with the fog of many years) when I would rush home from school, fire up my Nintendo, and try to rescue Zelda from the evil clutches of Ganon.

To that end, I’ve created a simple jQuery plugin that can turn a JavaScript array into CSS pixel art. It looks like this:

See the Pen Pixelize jQuery Plugin by Rob Glazebrook (@rglazebrook) on CodePen.

Read On…

Simple Table Column Highlighting

Published January 6, 2014 by saurav.roy.

A table with the third column and second row highlighted.

Though they’re often treated like the redheaded stepchild of modern web design, tables are still one of the best ways of displaying concise tabular data. But the more data that gets packed into a table, the tougher they get to read. Zebra striping the rows helps some, and column striping can help even more.

One design technique I’ve always enjoyed is highlighting the row and column of any cell that the user hovers over. Highlighting a cell’s row is simple, because table cells are organized into rows: all you have to do is apply a style to tr:hover, and you’re done. Columns are harder because there’s no inherent structure for a column in a table, which means loads of complex JavaScript is inevitable. Or so I thought.

I’ve been building HTML tables for nearly two decades now. Today I realized two things:

  1. There’s such a thing as a col tag for tables (who knew?).
  2. It’s going to make my life easier.

Read On…

Intelligent Select Box Filtering

Published July 16, 2010 by saurav.roy.

One of the great things about building websites for a living is the challenges tend to change from day to day. There’s always a new puzzle to solve.

Take today, for example. I was building a page that contained a series of select (dropdown) boxes. Now, I’ve been around the block once or twice before, and this wasn’t my first time using selects. However, this implementation came with a unique twist: all the boxes contained the exact same options, but we only wanted each to be selectable once. Specifically, each box contained a list of security questions — your mom’s best friend’s grandmother’s maiden name, that sort of thing.

The code looks something like this:

<select class="security" name="security1">
	<option value="0">Select a question.</option>
	<option value="1">Who's your daddy?</option>
	<option value="2">What's your favorite color?</option>
	<option value="3">What time is it?</option>
</select>
<select class="security" name="security2">
	<option value="0">Select a question.</option>
	<option value="1">Who's your daddy?</option>
	<option value="2">What's your favorite color?</option>
	<option value="3">What time is it?</option>
</select>

Now, naturally, we want the user to select several different security questions. But what’s to stop them from selecting the same question several times? Well, in our case, back-end validation… but I wanted to solve the problem before we got to that point. I wanted to eliminate “selected” questions from all the other dropdown boxes, so it wouldn’t even be an option. This has the added benefit of shortening the list of options as the user goes along, which would make scanning the options easier. Read On…

Cross-Browser Rounded Buttons with CSS3 and jQuery

Published April 22, 2010 by saurav.roy.

So here’s the scenario: I was tasked with replacing several dozen Photoshop-generated rounded buttons for a larger site with an HTML/CSS/JS equivalent. Prior, any time anyone wanted to change text on a button (and it seemed to happen often), a graphic designer had to fire up Photoshop, modify a file, adjust for size, output an image, and pass that file off to the person building the page. It was an involved process for something that should have been simple.

So let’s make it simple!

Right away I knew that I wanted to present as simple a solution for the developer as I could. I didn’t want to force them to use tons of extra markup in their HTML to pull this trick off. This was a piece of cake in modern browsers, as you’ll see in a moment. Unfortunately, this site also has a large IE user base, so I needed to account for less-modern browsers as well.

Border-Radius for Those Who Can

I decided I wanted to use border-radius for the rounded buttons for any browsers that could support it. I also decided that I wanted to create a single class, “button,” for any buttons, and it should work more-or-less the same on anchor tags, button tags, and “submit-type input tags. Read On…

Test for Border-Radius Support

Published April 15, 2010 by saurav.roy.

Of all the fantastic magical CSS3 properties out there, border-radius was one of the first I really latched on to. It made sense to me from the start, and I could see immediate practical uses (at least, as far as a border can be practical). If you’re not using the border-radius property yet, be sure to check out my article on how to use it.

Unfortunately, even though more advanced browsers started supporting border-radius years ago, not all browsers are up to speed yet. As of this writing, border-radius is supported in Webkit (Safari/Chrome), Firefox, and rumor has it Konqueror, though I don’t have a Linux install so I can’t prove that. That leaves Opera and Internet Explorer out of the game – I’ve heard rumors that Opera will support border-radius soon, but the latest version is still a no-go.

As I argued in my last article on the topic, most of the places people should use rounded corners today fall into the realm of “progressive enhancement”: the site looks better with the element rounded, but it’s not the end of the world if someone sees a square corner.

Of course, what should be true and what a client requires aren’t always the same thing. Read On…

How To Emulate a Foreach Loop in JavaScript

Published January 21, 2010 by saurav.roy.

JavaScript does many things well, but one area I’ve always had trouble with is the array and array-manipulation department. For example, this weekend I was working on a project that required me to iterate through a JavaScript array and peform a set of functions on the values within. In PHP, that would have looked something like this:

$myArray = array("item 1", "item 2", item 3");
foreach($myArray as $item) {
	$item = "Do Something Here";
}

Nice and simple, right? All we’re doing is iterating through the array with the foreach() construct and replacing each item with the phrase “Do Something Here,” but you can see how this could/would expand. A similar construct exists in Perl, another language I grew up on.

But JavaScript lacks a specific “foreach” statement, which trips me up every time. So how do we fake it? Read On…

Improve Usability and CTR: Make an Entire List Item Clickable

Published January 12, 2010 by saurav.roy.

I was recently working on the navigation for a new WordPress site (to be announced later) and I encountered a bit of a conundrum when it came to my category navigation.

I had developed some snazzy PHP/WordPress scripting to output my category information into a list containing both the category name as well as the category description. It was a nice way to show people what categories the site had, as well as offering some insight into what the category might contain. The code looked something like this: Read On…

The Best CSS Newbie Articles of 2009

Published January 5, 2010 by saurav.roy.

Happy 2010, readers of CSS Newbie! It’s a bitterly cold day here in Des Moines, Iowa — the sort that causes me to question the wisdom of throwing off the blankets in the morning. However, today I get to reflect on the last year of CSS Newbie, and that’s enough to warm my heart, if not my toes.

I’ve said it before and I’ll say it again: CSS Newbie is nothing without you awesome readers out there. This year, more than a quarter million people stopped by, visiting more than half a million pages. For that, I am very, very grateful. It also makes me excited to see what we can do for those numbers in 2010!

To celebrate the year gone by, I’d like to recap the Top 10 CSS Newbie Articles of 2009. The first five I’ve left up to you — they’re the five most visited articles in the last year. The second five were my choice. They include articles I enjoyed writing or include content that I thought particularly useful or interesting. Read On…

How To Create Simple, Stylish and Swappable Image Captions

Published December 3, 2009 by saurav.roy.

Image Captions

While they say a picture is worth a thousand words, not every image is self-explanatory. Sometimes a few words of description or context can make the difference between a confusing image and a clarifying one. That’s why image captions are often a good idea.

I’ve always liked the idea of giving images captions, but I rarely do. And why not? It seems to me that most image caption solutions out there:

  • Require a lot of excess HTML,
  • Make it difficult to redesign (because of the rigidity, usually),
  • Don’t make the relationship between image and caption clear, or
  • All of the above.

Today, I propose a solution that addresses many — if not all — of these concerns. Read On…