How to conditionally add a member to a JavaScript object?

This article describes how to add a member to a JavaScript object only if a condition is met. We demostrate it in pure JS and also in JQuery.

Pure JavaScript version

In pure javascript, the most compact solution I could come up with is this:

var myObject = {};

if(true) myObject.member1 = 10;
if(false) myObject.member2 = 20;
if(true) myObject.member3 = 30;

In this example only the first and third member will be added. It is quite okay, but looks a bit verbose, especially because all of the assignments are separate statements, and you have to write down the name of the object multiple times. It would be good to have a solution that can handle conditional adding when declaring the object. Let’s look at jQuery…

jQuery version

As you might expect, in jQuery it is a bit more compact. Let’s see the solution:

var myObject = $.extend({}, {
    member1: true  ? 10 : undefined,
    member2: false ? 20 : undefined,
    member3: true  ? 30 : undefined,
});

As you can see, it looks better, and you can assign the members when you are creating the object. However, you have to write undefined in all places, but even considering that, it is a more compact solution.

This code uses the extend function that can add the members of one JavaScript object to another JavaScript object. As you can see we set all the attributes of the second object, but only the ones that have a value that is not undefined will be set.

JavaScript trim function is not working in IE8

If you are trying to use JavaScript’s trim() function on strings in IE8, you will see, that it throws an error like this:

Message: Object doesn't support this property or method
...

This is because this function is not supported in IE8, even this Microsoft documentation page proves it.

However, there are workarounds of course. Either you can define the trim() function, or you can use jQuery’s trim().

Defining the trim function

To define the trim function on strings, you need to add the following code:

if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}

This code uses a regular expression to remove the leading and trailing whitespaces from a string. The if condition makes sure that it is only defined if it does not exist in the first place.

Using jQuery’s trim()

The popular jQuery library contains an implementation of the trim function, so you could use that one too. It is used in a bit different way, because it is not a function on String objects, but it expects the string as a parameter, and returns with the trimmed value. Use it like this:

$.trim( $("#myID").val() );

 

Make column scrollable if it’s higher than other column

This tutorial explains how to create a two-column layout, where one of the columns become scrollable if it’s height would exceed the other column’s height.

There are two possible variations of this. Either the left or the right column is scrollable. These require slightly different solutions on the CSS side, so I will explain each of them separately.

The idea behind our solution

Basically we are just taking advantage of the properties of the absolute and relative positioning.

We will use two elements inside a container. One of the elements will use the default static positioning and is able to push the height of the container out depending on it’s content.

The other element will have absolute positioning so it is taken out of the normal flow, and unable to alter the height of it’s parent. What we will do with this absolute positioned element is that we make sure it’s height is 100% of the parent’s height and force the content to scroll instead of overflowing.

So this way, our relative element will control the height of the container, and the other element will adapt to it’s height, and if it would exceed it, we make it scrollable by setting the overflow-y property to auto.

We used background color on our elements in the upcoming demonstration, but they are just there so the outcome is more visually apparent. Also, the widths of the elements can be changed, they don’t have to be 50-50%, as in the example.

Our HTML structure

The HTML structure we use will be the same in both cases, so this is the first thing I show you.

<div class="container">
    <div class="left">...</div>
    <div class="right">...</div>
</div>

We have a container and two columns that are div elements in this case, but you can use other block level elements if you wish. The left and right columns should have some content depending on which of the two cases you would like to demonstrate. Use longer content in the div that you would like to make scrollable.

Making the left column scrollable

left-column-scrollable

Here is the CSS that makes the left column scrollable.

.container { 
    position: relative;
} 
       
.right { 
    width: 50%;
    margin-left: 50%;
    background-color: #E0E0B5;  
}

.left {
    width: 50%;
    background-color: #B5D8E0;
    position: absolute;
    overflow-y: auto;    
    height: 100%;
}

Notice that we are using a 50% margin on the right element, so it is positioned in the proper place.

Making the right column scrollable

right-column-scrollable

Here is the CSS that makes the right column scrollable.

.container { 
    position: relative;
} 
       
.right { 
    height: 100%; 
    width: 50%;
    position: absolute; 
    right: 0;
    top: 0;
    overflow-y: auto; 
    background-color: #E0E0B5;
}

.left {
    width: 50%;
    background-color: #B5D8E0;
}

You can see, that it’s really similar to the previous example, but we are using the right and top properties, to position the right side element the correct way.

Browser support

This solution has been tested and it works in the latest Chrome, Firefox, and in IE 8-11.

Change the text of a link via CSS

A typical example of a link that changes it’s text is when you would like to create section on your website and need a link that says Collapse when the section is open and says Expand when the section is closed.

Create a simple closable section

First, let’s create a simple link that will open and close our section with the help of a little JavaScript. The HTML part:

<a class="toggle-button" href="#">Collapse/Expand</a>

<section class="expandable">
    This is an expandable section.
</section>

The JavaScript part:

$(function() {
    $('.toggle-button').on('click', function() {
    	$('.expandable').toggle();
    });
});

Clicking the link can open and close the section. So our program is working fine, but we could improve it a little bit by changing the text of the link depending on the status of our section.

Add text changing functionality via CSS

Let’s add a wrapper around our HTML elements and change the classnames:

<div class="expandable-container">
    <a class="toggle-button" href="#" data-collapsed="Expand" data-expanded="Collapse"></a>
    <section class="expandable-content">
        This is an expandable section.
    </section>
</div>

Our JavaScript will also need to be changed, because we would like to add the expanded class to the parent of the content that we would like to show/hide.

$(function() {
    $('.toggle-button').on('click', function() {
        $(this).parent().toggleClass('expanded');
    });
});

Now comes the most important part. As you can see in our HTML we provided the Expand and Collapse texts is data attributes. We will use CSS to read these attributes and set them as the link’s text.

.expandable-container .toggle-button:after {
    content: attr(data-collapsed);
}
.expandable-container.expanded .toggle-button:after {
    content: attr(data-expanded);
}

.expandable-container .expandable-content {
    display: none;
}

.expandable-container.expanded .expandable-content {
    display: block;
}

The text of the link is set using the :after psedo attribute. The content inserted this way should behave as it would be a normal child of the element, but some browsers have issues interpreting them. In an other article I discussed a possible problem that could come up on certain browsers: Link with pseudo attribute is not clickable on mobile browser (Samsung Galaxy S3)

Link with pseudo attribute is not clickable on mobile browser (Samsung Galaxy S3)

Samsung Galaxy SIII

The Samsung Galaxy S3 and S3 Mini’s browser (and possibly other devices as well) produce a strange issue that causes links not to be clickable if the text of the link is set using pseudo attributes. Here is some sample code that can produce this issue.

The HTML:

<a class="link" href="http://www.google.com" data-collapsed="Expand" data-expanded="Collapse"></a>
The CSS:
.link:after {
    display: inline;
    content: attr(data-collapsed);
}

.link.expanded:after {
    display: inline;
    content: attr(data-expanded);
}

In this example, by default the link’s text will be Collapse, but if the expanded class is added to the link, it’s text changes to Expand.

However, this does not work correctly on Samsung Galaxy S3 and S3 Mini. The text of the link is displayed correctly in both cases, but it is not clickable.

To solve this issue you need a strange workaround. Set the background color of the link. It can be invisible if you don’t really want a background, but the background must be set.

.link {
    background: transparent url("") no-repeat;
}