Category: JavaScript

JavaScript: how to check if a string variable is an integer value

JS on yellow background

One way to check if a variable is of type integer, Number.isInteger() can be used:

Number.isInteger(22); // true
Number.isInteger(22.2); // false
Number.isInteger('22'); // false

But this solution has the disadvantage, that a string with integer value like '22' will result in false.

To address this case, another solution is required:

function isInteger(data) {
  return +data === parseInt(data);
}

isInteger(22); // true
isInteger(22.2); // false
isInteger('22'); // true

This will result in true for integer 22 as well as a string '22'.

 

JavaScript: the differences between escape(), encodeURI(), and encodeURIComponent()

minimized programming code

In JavaScript, escape(), encodeURI(), and encodeURIComponent() are three functions used to encode strings for different purposes. Each function serves a distinct purpose, and it’s essential to understand their differences:

escape()

The escape() function is used to encode a string so that it can be safely included in a URL query string. It encodes special characters, except for alphanumeric characters and the following set of symbols: @*_+-./. The main drawback of escape() is that it does not encode all characters, and it’s considered deprecated in favor of encodeURIComponent().

Example:

const originalString = "Hello, World!";
const encodedString = escape(originalString);
console.log(encodedString); // "Hello%2C%20World%21"

encodeURI()

The encodeURI() function is used to encode a complete URI (Uniform Resource Identifier) but leaves the special characters used in the query string (?, &, =, etc.) untouched. It is primarily used to encode the main part of a URL, such as the protocol, domain, and path.

Example:

const originalURI = "https://www.example.com/my page.html?name=John Doe";
const encodedURI = encodeURI(originalURI);
console.log(encodedURI); // "https://www.example.com/my%20page.html?name=John%20Doe"

encodeURIComponent()

The encodeURIComponent() function is used to encode a component of a URI, such as a query parameter, fragment identifier, or any part that needs to be included in the query string. Unlike encodeURI(), this function encodes all special characters to ensure they are safely passed as parameters in a URL.

Example:

const originalParameter = "John Doe";
const encodedParameter = encodeURIComponent(originalParameter);
console.log(encodedParameter); // "John%20Doe"

In summary

Use escape() for encoding a string to be safely included in a query string, but it’s deprecated and not recommended for general use.

Use encodeURI() for encoding a complete URI (protocol, domain, path) but not the query string parameters.

Use encodeURIComponent() for encoding individual components (e.g., query parameters) of a URI to ensure all special characters are encoded properly. This is the most commonly used encoding function for URLs.

Foto von Markus Spiske auf Unsplash

 

jQuery methods in plain JavaScript

cup of coffee

Life is already very complex, so let’s simplify your projects by removing all the jQuery code. Plain JavaScript provides the same functionalities and it does not require any additional frameworks. And it’s supported by most of the modern browsers out of the box. This is a list of replacements for your daily used jQuery methods.

$() or jQuery()

Return a collection of matched elements either found in the DOM based on passed argument(s) or created by passing an HTML string.

// jQuery implementation
var element = $(selector);
// Plain JavaScript
var element = document.querySelector(selector); // Single element
var elements = document.querySelectorAll(selector); // Multiple elements

.addClass()

Adds the specified class(es) to each element in the set of matched elements.

// jQuery implementation
element.addClass('text-bold');
// Plain JavaScript
element.classList.add('text-bold');

.attr()

Adds the specified class(es) to each element in the set of matched elements.

// jQuery implementation
element.attr(attribute, value);
// Plain JavaScript
element.setAttribute(attribute, value);

.css()

Set one or more CSS properties for the set of matched elements.

// jQuery implementation
element.css(property, value);
// Plain JavaScript
element.style[property] = value;

.each()

Iterate over a jQuery object, executing a function for each matched element.

// jQuery implementation
$.each(settings, function (index, element) {
    // ...
});
// Plain JavaScript
settings.forEach((element, index) => {
    // ...
});

.empty()

Remove all child nodes of the set of matched elements from the DOM.

// jQuery implementation
container.empty();
// Plain JavaScript
container.replaceChildren();

See https://stackoverflow.com/a/65413839/768352

.extend()

Merge the contents of two or more objects together into the first object.

// jQuery implementation
const settings = $.extend(defaults, options)
// Plain JavaScript
const settings = {...defaults, ...options}

.hasClass()

Determine whether any of the matched elements are assigned the given class.

// jQuery implementation
if (element.hasClass('text-bold')) {
  // ...
}
// Plain JavaScript
if (element.classList.contains('text-bold')) {
  // ...
}

.hide()

Hide the matched elements.

// jQuery implementation
element.hide();
// Plain JavaScript
element.style.display = 'none';

.html()

Set the HTML contents of each element in the set of matched elements.

// jQuery implementation
element.html('<div>my html</div>');
// Plain JavaScript
element.style.innerHTML = '<div>my html</div>';

.map()

Translate all items in an array or object to new array of items.

// jQuery implementation
$.map(array, function (value, index) {});
// Plain JavaScript
array.map((value, index) => {});

.now()

Return a number representing the current time.

// jQuery implementation
$.now();
// Plain JavaScript
Date.now();

.removeClass()

Remove a single class or multiple classes from each element in the set of matched elements.

// jQuery implementation
element.removeClass('text-bold');
// Plain JavaScript
element.classList.remove('text-bold');

.show()

Display the matched elements.

// jQuery implementation
element.show();
// Plain JavaScript
element.style.display = 'block';

.text()

Set the content of each element in the set of matched elements to the specified text.

// jQuery implementation
element.text('my text');
// Plain JavaScript
element.textContent = 'my text';

.toggle()

Display or hide the matched elements.

// jQuery implementation
element.toggle();
// Plain JavaScript
element.style.display = element.style.display === 'none' ? 'block' : 'none';

.toggleClass()

Add or remove one or more classes from each element in the set of matched elements, depending on either the class’s presence or the value of the state argument.

// jQuery implementation
element.toggleClass('text-bold');
// Plain JavaScript
element.classList.toggle('text-bold');

.trigger()

Execute all handlers and behaviors attached to the matched elements for the given event type.

// jQuery implementation
$(document).trigger("myEvent");
$(".container").trigger("myEvent");

// Plain JavaScript
document.dispatchEvent(new Event("myEvent"));
document.querySelector(".container").dispatchEvent(new Event("myEvent"));

.val()

Get the current value of the first element in the set of matched elements.

// jQuery implementation
var val = element.val();
// Plain JavaScript
var val = element.value;

Photo by Jakub Dziubak on Unsplash

JavaScript: simple code structure for libraries

macbook pro on a table

The code of a JavaScript library might get very complex over time. This can be a problem for maintenance and expandability.

When writing a library, you should address two main points:

  • Keep the environment clean from global variables and methods to avoid conflicts between different libraries
  • Provide public and private methods and variables

The following “template” provides a simple code structure that fulfills those points:

// Unique name of the library.
MyLibrary = function() {
  MyLibrary = {};

  /*
   * Internal variables and methods
   */
  var variable = 'value';
  function doSomething() {
    // do something
  }

  /*
   * Public variables and methods
   */
  MyLibrary.myVariable = true;
  MyLibrary.myAction = function() {
    // do something
  }

  // Return the library.
  return MyLibrary;
}

You can use such a library the following way:

const lib = MyLibrary();
lib.myAction()

if (lib.myVariable) {
  alert('really?');
}

Inspiration: https://stackoverflow.com/questions/13606188/writing-a-library-what-structure

Photo by Safar Safarov on Unsplash

JavaScript: String in String suchen

Eine Zeichenkette (String) lässt sich in einem anderen String wie folgt suchen:

if (str.indexOf("Ja") >= 0)

…oder über den Tilde-Operator*:

if (~str.indexOf("Ja"))

Diese beiden Varianten berücksichtigen jedoch keine Groß- und Kleinschreibung!
Die Berücksichtigung von Groß- und Kleinschreibung kann man erreichen mit:

if (str.toLowerCase().indexOf("ja") >= 0)

…oder über reguläre Ausdrücke:

if (/ja/i.test(str))

* Was macht der Tilde-Operator?

Der Tilde-Operator kehrt eine Bit-Folge um, also 1 > 0 und 0 > 1. Wenn der Rückgabewert von ‘indexOf’ -1 ist, dann führt ~-1 zu 0, weil -1 komplett aus 1 Bits besteht. Jeder Wert größer oder gleich 0 wird als Rückgabe einen Nicht-Null-Wert geben.

HTML5 Boilerplate – das Grundgerüst für HTML5

HTML5 Boilerplate bietet ein kompaktes Grundgerüst zum Gestalten von Webseiten oder wie auch ich es nicht besser ausdrücken kann:

HTML5 Boilerplate ist ein professionelles HTML/CSS/JS-Template als Basis für eine schnelle, robuste und zukunftssichere Website.
Nach mehr als zwei Jahren Entwicklung, bekommt ihr das beste der besten Techniken zusammengefasst: Cross-Browser-Normalisierung, Performance-Optimierungen und sogar optionale Features wie Cross-Domain AJAX und Flash. Eine starter .htaccess-Konfigurationsdatei kommt mit praktischen Caching-Regeln, bereitet deine Seite für HTML5-Video vor und erlaubt dir einfache @font-face-Nutzung und gzip-Auslieferung deiner Ressourcen.
Boilerplate ist weder ein Framework, noch schreibt es dir eine Entwicklungsphilosophie vor. Es ist eine Sammlung von Tipps und Tricks, die dir helfen sollen, dein Projekt schnellstmöglich und flexibel auf die Beine zu stellen.

… ohne dabei eine Menge Zeit in die Anpassung einer Webseite an die verschiedensten Browser zu vergeuten. Weitere Informationen gibt es auf http://html5boilerplate.com/.

Web-Development: eine Sammlung an hilfreichen Tutorials und Webseiten

Auch beim Gestalten von Webseiten gibt es immer wieder Dinge, welche schon einmal irgendwo in den tiefen des Internet beschrieben wurden. Damit das Rad also nicht neu erfunden werden muss, hier eine Liste mit hilfereichen Tutorials, wenn es um Web-Development geht. Neben allgemeinen Themen zum Webdesign soll es hierbei auch um die Verwendung der aktuellen Standards von HTML5 und CSS3 gehen.

jQuery: prüfen, ob ein Elemtent sichtbar (visible) ist

Verwendet man JQuery’s Effekte, wie beispielsweise JQuery.slideToggle(element), dann kann man die CSS-Eigenschaft visibility hier nicht nutzen, um zu ermitteln, ob das Element “ein- oder ausgeklappt” ist. Das Element ist dann möglicherweise ausgeblendet (minimiert), aber die Eigenschaft auf visibility:visible gesetzt.
Wie lässt sich nun ermitteln, ob das Element ausgeblendet wurde?