April 30, 2024

CSS Properties - Inherit, Initial and Unset Values

All CSS properties have 3 basic values in common: inherit, initial and unset.

Here is quick summary for these values:

  • initial: The default value for the property (the browser default).
  • inherit: Get the property from the parent element.
  • unset: Acts as either inherit or initial. It’ll act as inherit if the parent has a value that matches, or else it will act as initial.

Example CSS:

    <style>
        div {
            color: red;
            font-size:larger;
        }

        .some-design {
            color: blue;
        }

        .unset {
            color: unset;
        }

        .initial {
            color: initial;
        }
    </style>

Example HTML:

    <div>
        <div>Text in this (parent) div element is red.</div>
        <div class="some-design">This div's css make it blue.</div>
        <div class="unset">(color => unset): The color is unset 
             (red, because it is inherited from the parent div).</div>
        <div class="initial">(color => initial): The color is initial 
             (black, the browser default).</div>
    </div>

It will display the output like:

JS Geolocation API – Use watchPosition()

The watchPosition() method of the Geolocation interface is used to register a handler function that will be called automatically each time the position of the device changes. You can also, optionally, specify an error handling callback function.

This method retrieves periodic updates about the current geographic location of the device, allows to detect a change in position of device. The location object contains geographic coordinates with information about speed.

Like we have 3 parameters in getCurrentPosition() method, watchPosition() accepts the same:

  • success: A callback function that retrieves the location information.
  • error (Optional): An optional callback function that takes a GeolocationPositionError object as an input parameter.
  • options (Optional): This optional parameter specifies a set of options for retrieving the location information.

    You can specify:

    • Accuracy of the returned location information
    • Timeout for retrieving the location information
    • Use of cached location information
Return value: An integer ID that identifies the registered handler. The ID can be passed to the Geolocation.clearWatch() to unregister the handler and stop receiving location updates.

Example Code:

function onSuccess(position) {
	//do something with position data.
	console.log("Latitude: " + position.coords.latitude);
	console.log("Longitude: " + position.coords.longitude);
}

function onError(error) {
  switch(error.code) {
    case error.PERMISSION_DENIED:
      console.log("User denied the request for Geolocation.");
      break;
    case error.POSITION_UNAVAILABLE:
      console.log("Location information is unavailable.");
      break;
    case error.TIMEOUT:
      console.log("The request to get user location timed out.");
      break;
    case error.UNKNOWN_ERROR:
      console.log("An unknown error occurred.");
      break;
  }
}

// Options: throw an error if no update is received every 30 seconds.
var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 });

Related Post(s):

March 21, 2024

JS Geolocation API – getCurrentPosition with options parameter

In the last post (JS Geolocation API – Get a User's Location) we have covered navigator.geolocation.getCurrentPosition() method to get user's location. We have used the success and error callbacks to receive the position object or report error.

The method getCurrentPosition() also accepts an options object as third paramter (optional).

This options object allows you to specify:

  • enableHighAccurancy (default false): if set to true, response is slower and more accurate.
  • maximumAge (default 0): milliseconds when cached value is valid, the device may decide to use valid cached data instead of sensor measure. Represents age for the returned position value (up until this age it will be cached and reused if the same position is requested again, after this the browser will request fresh position data)
  • timeout (default infinity): milliseconds before the API gives up and calls the error handler (the second parameter).

The example below calls getCurrentPosition() with both success and error callbacks, and pass the options object in third argument:

var options = {
  enableHighAccuracy: true,
  timeout: 5000, //timeout 5 seconds
  maximumAge: 10000 //(location) age 10 seconds
};

navigator.geolocation.getCurrentPosition(success, error, options);

Related Post(s):

JS Geolocation API – Get a User's Location

The JavaScript Geolocation API provides access to geographical location data associated with a user's device. This can be determined using GPS, WIFI, IP Geolocation and so on.

Geolocation is most accurate for devices with GPS, like smartphones.

To protect the user's privacy, it requests permission to locate the device. If the user grants permission, you will gain access to location data such as latitude, longitude, altitude and speed etc.

The Geolocation API is available through the navigator.geolocation object.

If the object exists, geolocation services are available. You can test for the presence of geolocation:

if ("geolocation" in navigator) {
  console.log("geolocation is available");
} else {
  console.log("geolocation is not available");
}

navigator.geolocation object provides the method getCurrentPosition() to return the user's position.

There are three possible arguments with this method:

  • A success callback (required)
  • An error callback (optional)
  • An options object (optional)

The example below calls getCurrentPosition() with both success and error callbacks, and returns the latitude and longitude of the user's position:

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(usePositionData, useError);
  } else {
    console.log("Geolocation is not supported by this browser.");
  }
}

function usePositionData(position) {
	//do something with position data.
	console.log("Latitude: " + position.coords.latitude);
	console.log("Longitude: " + position.coords.longitude);
}

function useError(error) {
  switch(error.code) {
    case error.PERMISSION_DENIED:
      console.log("User denied the request for Geolocation.");
      break;
    case error.POSITION_UNAVAILABLE:
      console.log("Location information is unavailable.");
      break;
    case error.TIMEOUT:
      console.log("The request to get user location timed out.");
      break;
    case error.UNKNOWN_ERROR:
      console.log("An unknown error occurred.");
      break;
  }
}

Related Post(s):

February 27, 2024

CSS - Using media query features

Media Query features define the style for specific characteristics of a given user agent, output device, or environment.

Media features can be either range or discrete.

Discrete features take their value from an enumerated set of possible keyword values. For example, the discrete orientation feature accepts either landscape or portrait.

@media print and (orientation: portrait) {
  colod: red;
}

Many range features can be prefixed with min- or max- to express "minimum condition" or "maximum condition" constraints. For example, this CSS will apply styles only if your browser's viewport width is equal to or narrower than 1000px:

@media (max-width: 1000px) {
  colod: blue;
}

An alternative syntax for above condition is to use ordinary mathematical comparison operators >, <, >=, or <=.

@media (width <= 1000px) {
  colod: blue;
}

@media (width <= 1000px) is the equivalent of @media (max-width: 1000px).

These are some other commonly used media features:

  • orientation: Orientation of the viewport (landscape or portrait)
  • max-height: Maximum height of the viewport
  • min-height: Minimum height of the viewport
  • height: Height of the viewport (including scrollbar)
  • max-width: Maximum width of the viewport
  • min-width: Minimum width of the viewport
  • width: Width of the viewport (including scrollbar)

Related Post(s):

CSS - Using media queries

Media queries allow you to conditionally apply CSS styles depending on a device's media type (such as screen, print). You can also specifiy other features or characteristics such as screen resolution or orientation etc.

A media query is composed of an optional media type and any number of media feature expressions, which may be combined using logical operators.

Media types describe the general category of a given device, mainly we are using three basic types screen, print, and all.

  • screen: used for websites commonly designed (for computer screens, tablets, smart-phones etc).
    @media screen {
      colod: red;
    }
    
  • print: used for printing (print preview mode)
    @media print {
      colod: blue;
    }
    
  • all: for all devies, there is no filter for any specific device category.
    @media all {
      colod: green;
    }
    
The mediatype is optional (if omitted, it will be set to all).
@media {
  colod: green;
}

You can also target multiple devices types. For instance, this @media rule uses two media queries to target both screen and print devices:

@media screen, print {
  colod: green;
}

Related Post(s):

January 28, 2024

git shows files as modified after adding to .gitignore

In Visual Studio, once the .Net project is setup with git, you might notice that it will keep track for extra files, like autogenerated files in obj/debug folders.

You can ignore these selected folders/files by using .gitignore file.

To ignore debug, release, bin and obj folders etc., you can make these entries in .gitignore file.

[Dd]ebug/
[Rr]elease/
[Bb]in/
[Oo]bj/

After settings these changes you might notice that git is still tracking the files in these folders.

The reason is that these are the changes before the .gitignore file is updated.

To fix this issue you need to removes all files that have been cached (as being 'tracked'), then re-add files based on the .gitignore file entries.

Here are the steps, notice the dot (.) in the end of first 2 commands, this . is part of command syntax:

  • Remove all files recursively from index that are cached (being tracked).
    git rm -r --cached .
    

    rm is to remove files, -r is to remove recursively.

  • Add all files that have changed (re-add the files). This command will add all files except those which are mentioned in .gitignore.
    git add .
    
  • This command will commit your files again and remove the files you want to ignore, but keep them in your local directory.
    git commit -am "Remove ignored files"
    

January 27, 2024

How to set up git server on local machine (Windows)

To configure git server on local windows machine, you can follow these steps:

Setup Git Server Repo:

  1. Go to folder, where you want to initialize the server, specify a name without spaces (else you will need to use quotes whenever accessing this folder)
  2. Open this folder in command prompt and type this command to initiate server repo.
    //git init <repo-name>.git --bare
    
    git init mylocalrepo.git --bare
    
    

    mylocalrepo is the repository name.

    (Note: to avoid any issues later, its better to append the suffix '.git' to the repository name)

The git server repo is setup.

Setup Git Client/Clone:

  1. Go to the folder, where you want to initialize the client.
  2. Open this folder in command prompt and type this command to initiate client repo.
    //git clone <path_to_your_server>
    
    git clone C:\_Data\Test\GitServer\mylocalrepo.git
    
    You may need to change the back-slash "\" to forward-slash "/" in the path.

The client repo is setup.

You can try to make chages in client repo and push to git server.

Manually create a new file (readme.txt) in client folder, and make some changes.

You can stage this file:

git add .

Commit the changes with custom message:

git commit -m "added readme file"

Push the changes to git server:

git push