Posts

Free WordPress Classic Widget (Plugin) Google Maps

Image
WS GMaps is a classic Google Maps widget (plugin) for the WordPress CMS. The widget allows you to set multiple points on the map. Furthermore, multiple widgets can be used on a single page. The plugin is free to download. To use the plugin, you must provide a JavaScript Maps API key for Google Maps. You can generate an API key in the Google Cloud Platform (https://console.cloud.google.com/). In the admin panel, the plugin settings look like this: If you are using the classic widget, the plugin settings in the admin panel will look like this: You can set a description for a point on the map that will appear when clicked. This marker description can use HTML. You can see how this works in the example. If there are multiple markers on the map, you can specify the map center in the designated fields. If the map center is not specified, the first marker will be used as the center. You can download the plugin for free and view the demo here – Get WS GMaps .

Adding a website to free directories

Submitting your website to online directories remains a valuable SEO technique, even in today’s world of constantly evolving search engine algorithms. While some marketers consider it an old-fashioned approach, directory submissions can still improve a website’s visibility and credibility when used strategically. Search engines treat high-quality directory listings as reliable backlinks, which help build your site’s authority and improve its ranking in search results. Directories act as a bridge between users and businesses, making it easier for potential customers to find your site within specific niches or regions. When your website is listed in relevant directories, it has a higher chance of attracting targeted traffic — people who are already interested in the products or services you offer. Additionally, listings in respected directories can generate referral traffic that comes directly from those platforms, not just from search engines. It’s important, however, to choose dir...

Closing a site with .htaccess

Image
The .htaccess file performs many different functions. This is an apache configuration file. Consider how to set a password for access to the site using .htaccess . This may be needed at design time or as an additional security tool. Video instruction To store the password (or passwords) from the directory, you need to create another file. Usually it is called .htpasswd , but you can call it differently. Put this file must be in the root of the site or above Sample entry in .htaccess AuthName "Authentication required" AuthType Basic AuthUserFile /home/yourdir/.htpasswd Require user yourlogin Set the password for yourlogin user in the .htpasswd file yourlogin:Mk5aMaDxjJch2 The link to generate passwords https://stringutils.online/htpasswd

Remove www in the site address, 301 redirects

A redirect is to redirect site visitors from one URL to another. 301 status indicates that the redirect is permanent. Removing www from the site address is necessary primarily for SEO . Since sites with www and without for search engines are different sites with the same content. For Apache server, you need to make an entry in the .htaccess file RewriteCond %{HTTP_HOST} ^www.example.com RewriteRule ^(.*)$ http://example.com/$1 [R=301,L] For NGINX , write in the site configuration file if ($host ~* www\.(.*)) { set $host_without_www $1; rewrite ^(.*)$ http://$host_without_www$1 permanent; } $host_without_www - write like that, this is a server variable

Ways to Create Objects in JavaScript

There are several ways to create objects in JavaScript . The Object data type plays a critical role in JS . An object is an unordered set of key-value pairs. May contain other objects 1. Literal notation var someObject_1 = {}; Perhaps the most common and easiest way. Let's add properties and methods someObject_1.name = "John"; someObject_1.age = 25; someObject_1.run = function(){ console.log("run") } And now the same thing, but we will set properties and methods when creating var someObject_1 = { name: "John", age: 25, run: function(){ console.log("run"); } }; 2. Object constructor This method is not recommended for use, and it is better to use the previous one. Nevertheless, it exists. But the probability of meeting him is extremely small var someObject_2 = new Object(); We also set properties and methods var someObject_2 = { name: "Nick", age: 30, jump: function(){ conso...

Configure https for Nginx

HTTPS is an advanced data transfer protocol that supports encryption. Install free ssl certificate from Lets Encrypt . Ubuntu server operating system Get a certificate sudo letsencrypt certonly -a webroot --webroot-path=/var/www/site.com/public_html -d site.com -d www.site.com Prolong sudo letsencrypt renew nginx config server { listen 80 ; server_name site.com.ru www.site.com; return 301 https://$server_name$request_uri; } server { # SSL configuration listen 443 ssl http2; listen [::]:443 ssl http2; server_name site.com www.site.com; ssl_certificate /etc/letsencrypt/live/site.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/site.com/privkey.pem; ssl_trusted_certificate /etc/letsencrypt/live/site.com/chain.pem; add_header Content-Security-Policy "img-src https: data:; upgrade-insecure-requests"; # We keep access log: access_log /var/log/nginx/site.com_access.log; # We share static and dynamic, static ...

PHP Data Caching

Sometimes it becomes necessary to limit the number of queries to an external data source. Especially if they do not change constantly. For example, the exchange rate in the central bank. Or simply speed up the page loading, giving the script an already generated file. $expires = 3600; //Cache lifetime in seconds $curTime = time(); $cacheFile = 'data.json'; function writeCache($cacheFile) { //get fresh data file_put_contents($cacheFile, file_get_contents('http://somesite.com/api')); } if (!file_exists($cacheFile)) { writeCache($cacheFile); } else { $fMtime = filemtime($cacheFile); if (($curTime - $fMtime) > $expires) { writeCache($cacheFile); } } This caching method is based on comparing the date of the file change with the cache with the current time.

Typical gulpfile.js

The file is written for Gulp 4 . The file is designed to work with styles ( SCSS ) and JavaScript . All minify and compile sourcemaps for debugging. Third-party scripts and styles are in separate files. const production = ( process.env.NODE_ENV == 'production' ); //base part let {src, dest, parallel, series, watch} = require('gulp'), rename = require('gulp-rename'), sourcemaps = require('gulp-sourcemaps'); //css part let sass = require('gulp-sass'), cleanCSS = require('gulp-clean-css'), autoprefixer = require('gulp-autoprefixer'); const babel = require('gulp-babel'), uglify = require('gulp-uglify-es').default, include = require("gulp-include"); let pathFiles = { build: { css: './css/', js: './js/' }, src: { css: './src/scss/**/*.scss', js: './src/js/**/*.js' } }; function swallowError(error){ ...

JavaScript Inheritance and Classes

In many programming languages implemented inheritance. And it also exists in JavaScript. First, consider prototype inheritance. We describe the function constructor function Animal(name, weight, color){ this.name = name || 'someAnimal'; this.weight = weight; this.color = color; //do some actions during initialization console.log(this.name + ' construct animal'); } // write the method to the prototype Animal.prototype.sayName = function(){ console.log(this.name); } We describe the constructor function that inherits the Animal class. And we will expand it, we will add in addition own properties and methods function Mammal(name, weight, color, limbs){ Animal.apply(this, arguments); this.limbs = limbs || 4; console.log(this.name + ' construct mammal'); } Mammal.prototype = Object.create(Animal.prototype); Mammal.prototype.constructor = Mammal; Mammal.prototype.run = function(){ console.log('run'); } Cre...

JavaScript Countdown Timer

Often on sites that sell something you can find a countdown timer to a certain date. Such a script is usually required for landing pages and online stores. JS (() => { let finishDate = new Date(2017, 8, 30); // set the final date let compareDate = finishDate.getTime(); let timer = setInterval(function () { timeBetweenDates(compareDate); }, 1000); function timeBetweenDates(toDate) { let difference = toDate - Date.now(); if (difference <= 0) { // if the date has passed, the timer stops clearInterval(timer); } else { let seconds = Math.floor(difference / 1000), minutes = Math.floor(seconds / 60), hours = Math.floor(minutes / 60), days = Math.floor(hours / 24); hours %= 24; minutes %= 60; seconds %= 60; if (days < 10) days = '0' + days; if (hours < 10) hours = '0...

Swipe events on touch devices

Every day sensory devices are being introduced into our lives. These devices have specific events, unlike the desktop. One of these events is the swipe . Especially often have to deal with it when developing a mobile version of the site. Code: (() => { let initialPoint; let finalPoint; document.addEventListener('touchstart', function(event) { initialPoint=event.changedTouches[0]; }, false); document.addEventListener('touchend', function(event) { finalPoint=event.changedTouches[0]; let xAbs = Math.abs(initialPoint.pageX - finalPoint.pageX); let yAbs = Math.abs(initialPoint.pageY - finalPoint.pageY); if (xAbs > 20 || yAbs > 20) { if (xAbs > yAbs) { if (finalPoint.pageX < initialPoint.pageX){ // to left } else{ // to right } } else { if (final...

AJAX with native JavaScript

Consider a few examples of working with AJAX with native JavaScript. Functions are written with ECMAScript-2015 syntax The function for the GET method: let ajaxGet = (url, callback) => { let xhr = new XMLHttpRequest(); xhr.onreadystatechange = () => { if (xhr.readyState == 4){ if(xhr.status == 200){ alert( xhr.responseText ); callback(); } else { // if error alert(xhr.statusText); } } }; xhr.open('GET', url, true); xhr.send(null); }; The function for the POST method. The data to be sent to the server accepts both the string and the object. let ajaxPost = options => { /* an example * options = { * data: 'a=1&b=word&c=name', * url: 'test.php', * cb: function(){ * alert('test'); * } * } */ let sendstr = ''...

Submitting Form Data with AJAX and jQuery

We will send form data without reloading the page using jQuery. We will not consider processing the server part. Sample form: <form id="test_ajax_form" method="post" action="test_handler_form.php"> <input type="text" name="name" placeholder="Name"> <textarea name="message" placeholder="Message"></textarea> <input type="submit" value="Send" name="submit"> </form> JS $(function(){ $('#test_ajax_form').on('submit', function(e){ e.preventDefault(); let data = $(this).serialize(), url = $(this).attr('action'); $.ajax({ method: "POST", url: url, data: data }).done(function(){ alert('Success!'); }).fail(function(){ alert('Error!'); }); }); });

Array max js

A short note about finding the maximum value in a JavaScript array with numeric values. The Array object in JS does not have its own max method. But we can add it. Array.prototype.max = function () { return Math.max.apply(null, this); } We borrowed the method we are interested in from the Math object. It will work like this: let arr = [3, 5, 6, 1, 10, '12', 0]; arr.max(); //12 If the array contains string values that cannot be cast to a number, the method returns NaN . You can do without modifying the global Array object. let arr = [3, 5, 6, 1, 10, '12', 56, 0]; Math.max.apply(null, arr); //56 And according to the syntax of ES6 you can write even easier let arr = [3, 5, 6, 1, 10, '12', 56, 0]; Math.max(...arr); //56

Cloning objects and arrays in JavaScript

For cloning objects in JS there is no specially provided method. You can copy an object in different ways. Since objects are passed by reference, we cannot clone simply by assigning a value to a variable. Objects With Spread let originalObject = {a: 1}; let clone = {...originalObject}; With Object.assign() let originalObject = {a: 1}; let clone = Object.assign({}, originalObject); With a loop let clone = {}; for (let key in originalObject) { if(originalObject.hasOwnProperty(key)){ clone[key] = originalObject[key]; } } With jQuery let clone = jQuery.extend(true, {}, originalObject); With lodash let clone = _.clone(value); let cloneDeep = _.cloneDeep(value); With JSON object let clone = JSON.parse(JSON.stringify(originalObject)); Arrays With Spread let clone = [...originalArray]; With Slice let clone = originalArray.slice(); Lodash can also be used for array cloning

Enumerating array elements without cycles

The examples are very abstract, since the cycles exist. You must select all the elements of the array for a given attribute. There are several solutions. The most appropriate option in PHP is to use the built-in function array_filter() . Imagine that it does not exist either. We write our using recursion. On PHP, the function looks like this: function getArrayElements ( $arr , $pattern ) { static $i = 0 ; static $arrayResult = [] ; if ( preg_match ( $pattern , $arr [ $i ] ) ) { $arrayResult [ ] = $arr [ $i ] ; } $i ++ ; if ( count ( $arr ) == $i ) { return ; } else { getArrayElements ( $arr , $pattern ) ; } return $arrayResult ; } Example: $arr = array ( 'a' , 'xd' , 'w' , 1 , 'y' , 'x' ) ; $pattern = '/^x/' ; print_r ( getArrayElements ( $arr , $pattern ) ) ; // Array ( [0] => xd [1] => x ) Now let's look at the same ...

How to push a footer to the bottom

 There are several ways. All of them are somewhat similar. The first option is the most relevant. Option 1 HTML < html > < body > < div class = " content " > </ div > < footer > </ footer > </ body > </ html > CSS body, html { height : 100% ; } body { display : flex ; flex-direction : column ; justify-content : space-between ; } Option 2 A footer height must be fixed HTML < html > < body > < div class = " content " > < main class = " main " > </ main > </ div > < footer class = " footer " > </ footer > </ body > </ html > CSS html,body { height : 100% ; } .content { min-height : 100% ; } .main { padding-bottom : 200px ; } .footer { height : 200px ; margin-top : -200px ; } Option 3 A footer hei...

Vertical alignment

There are several ways of vertical alignment. In different situations, different ways are suitable. Consider some of them. 1. With display: flex It's the most convenient and modern way .parent { display : flex ; align-items : center ; } 2. With table-cell In table cells, vertical-align applies to any content. .parent { display : table ; } .child { display : table-cell ; vertical-align : middle ; } 3. With position: absolute и top It is suitable for cases with a known height of the child block. The principle of operation lies in top: 50% (half of the parent block) and a negative indent from above into half of the child block. In the same way, you can center the block horizontally, using only left: 50% and a negative margin on the left. .parent { position : relative ; } .child { position : absolute ; height : 50px ; top : 50% ; margin-top : -25px ; } 4. With position: absolute and margin There is another way...

Simple JavaScript clock

Although this code can easily be found on the Internet, we still write a simple JavaScript clock Clock: < div id = " clock " > </ div > < script > function clock ( ) { let date = new Date ( ) , hours = date . getHours ( ) , minutes = date . getMinutes ( ) , seconds = date . getSeconds ( ) ; if ( hours < 10 ) hours = '0' + hours ; if ( minutes < 10 ) minutes = '0' + minutes ; if ( seconds < 10 ) seconds = '0' + seconds ; let time = hours + ':' + minutes + ':' + seconds ; document . getElementById ( 'clock' ) . innerText = time ; setTimeout ( ( ) => { clock ( ) ; } , 1000 ) ; } clock ( ) ; </ script >