07 June 2017

Highlighting text parts

 

Introduction

Ever used <Ctrl> + <F> to find something in your page? Why do you use it? Because you want to highlight your search. A small JS can do the trick as well.

Requirements

jQuery

Code

function highlight() {
        // containers to search in
        var searchInto = $("div, p, td, h1, h2, h3, h4");
        var args = arguments;
        $(searchInto).each(function () {
            // mark the items only if there is no additional html in it
            // it could destroy the layout otherwise

            if ($(this).html() == $(this).text()) {
                for (var i = 0; i < args.length; i++) {
                    var oldValue = $(this).html();
                    // making the searchstring red
                    var newValue = "<span style=\"color: red;\">" + args[i] + "</span>";
                    // replacing all
                    $(this).html(oldValue.replace(args[i], newValue, "g"));
                }
            }
        });
    }

// call it, with as many searchstring as you wish
highlight("poop", "view", "dog");

02 March 2017

Pissing-me-off moving button

 

 Introduction

Another funny script. Each time you enter a button with your mouse, the button moves to a random location making it impossible to click. Can be very annoying. But a fun idea for April's fool!

Requirements

jQuery

Code

(function jumpingButton() {
        // getting window size
        var windowsize = { height: $(window).height(), width: $(window).width() };
        // affecting all buttons
        $('button, input[type="submit"], input[type="image"]').mouseover(function () {
            $(this).offset({
                top: Math.round(Math.random() * windowsize.height),
                left: Math.round(Math.random() * windowsize.width)
            });
        });
    })();

30 August 2016

Protecting forms with negative-Capchas

 

Problem

Every form is a target of Spam-Bots. But how to protect your web from those evil bastards?
Captcha is the most common method preventing those machines from using your forms. An image with a number or a word is created that is readable for humans but not for the automated systems. Only if you type the word correctly in a text field, the form is sent.

Efficient. But quite uncomfortable for the user. There is an easier way. But first... let's have a look, how a spam-bot works.


A bot identifys a form and fills out every input-field, selects an option of every dropdown, checks every checkbox possible. If a field has the name "email" or is defined as type="email" it simply generates a fictional but valid e-mail address. They a programmed efficient. Just filling every input and try sending it. Some of them can even identify fields that required numbers like zip-codes.

Solution

So we can use this method against it. Just create a text-field that needs to be left blank. Then you can create a container around it, that hides it when you use a common browser. All you have to do now is check the field on server-side if it is left blank.

Requirements

A way to validate the inputs on the server side.

Example

 ...
<style type="text/css">
    .forthebot
    {
        display: none;
    }
</style>
...
<form action="" method="post" name="form1">
    <div>
        <label for="email">Enter your e-mail</label>
        <input type="email" id="email" name="email" placeholder="E-Mail" />
    </div>
    <!-- Here comes the Spam-bot trap -->
    <div class="forthebot">
        <label for="bot">Please leave this field blank</label>
        <input type="email" id="bot" name="bot" placeholder="Leave blank" />
    </div>
    <input type="submit" value="Send" />
</form>

06 July 2016

Show everyone my passwords


 

 Introduction

Every seen this fancy checkbox on mobile devices where you can make password fields visible? Well on a page for a desktop browser it doesn't really make sense. But hey, I'll show you how to do it anyway.

How it works

With the help of jQuery we collect all the password fields. It's just a text-input-field of type password. If we change the type from 'password' to 'text' all user input will be visible.

Requirements

jQuery

Code

    // global variable to undo what we've done
    var pwFields = undefined;

    // this function does the magic
    function togglePWFields() {
        if (!pwFields) {
            // finding all pw-fields
            pwFields = $("input[type=password]");
            $(pwFields).each(function () {
                // convert all those fields to text-fields
                $(this).attr("type", "text");
            });
        }
        else {
            $(pwFields).each(function () {
                // undo all
                $(this).attr("type", "password");
            });
            // reset stuff
            pwFields = undefined;
        }
    }

05 June 2016

Accessing the local storage

 Introduction

Sometimes it's quite useful to store some information on the visitors computer. Maybe you want to store the whole shopping cart on the computer. Maybe you make a website, where you can change the background color to pink for yourself. Maybe you want store the highscore of klicking the "Get me out of here"-button.
A common method is storing the information in a cookie. Yeah, you probably heard of those evil cookies that's only purpose is to get ALL of your personal information, like your prefered socks color, your credit card number and which super hero you are. Like your mother warned you about playing with the neighbours kid, some "IT specialists" warn you about accepting cookies.
Here comes the fun fact. We won't using cookies. Although it will work the same way.

What can it do?

The local storage is a key-value based database that modern browsers (and the IE) implements. Like cookies, the storage is bound to your website. When you store data in it, it cannot be recieved though another website.

The local storage is called localStorage (oh wonder..) and is a child of the window object. It has only four methods.

For storing
window.localStorage.setItem(<key>, <value>)

For recieving the value
window.localStorage.getItem(<key>)

For deleting a key-value pair
window.localStorage.removeItem(<key>)

For flushing all your stored data down the toilet
window.localStorage.clear()

You can save text in it. Not much? Want store complex objects? Easy! Use JSON to store and recover your objects.

Requirements

None. You just need JS and a browser, that supports localStorage.

Code

In this example you have an input where you can type in a message. With the save-button you store the message in the storage. With the load-button you can retrieve the message and put it in the text field again.
Although localStorage doesn't need any jQuery, we use it to minimize the code.

html
<input type="text" id="vault" />
<button onclick="save();retur

n false;">Save</button>
<button onclick="load();return false;">Load</button>

js
function save() {
        // saving what's in the input-field "vault" to the "myVault" in the local storage
        window.localStorage.setItem("myVault", $("#vault").val());
    }

    function load() {
        // retrieving what's in the myVault" of the local storage and put it in the input "vault"
        $("#vault").val(window.localStorage.getItem("myVault"));
    }


Be aware!

Not all browsers support the local storage. If you want to use it, mage certain it will work in your site.
How to check it? Simple...
js
if(window.localStorage){
    // shit works
}
else{
   // here, we have a problem...
}

29 April 2016

Preventing right-click

 

Introduction

Want to prevent someone copying images from your website? Well, you can't! But you can make it harder to call for the contextmenu with the mouse. Javascript can react on the event. So you can say: "Hey! Just do nothing, when someone wants to see the right-mouse-click-menu.

Required

I'll show you two versions. One requires only Javascript itself. The other one works with jQuery.

JS

window.oncontextmenu = function () {
        return false;
}

jQuery

$("*").contextmenu(function(){
        return false;
});

or

$("*").on("contextmenu", function () {
       return false;
});

31 March 2016

Validate a date - the simple way

 

 Introduction

How do you check if a date is valid? Let's see... Does the month selected has 30 or 31 days. But wait... there is the february it has only 28 days. And all 4 years there is a leap year. Except every 100 years. Pretty complex, isn't it?
But, there is a simple way!

How it works

Funny thing about Javascript is that you can create a date even with invalid values. It converts it into a valid date.
For example. If you want to create the date 32nd of March, it will make the 1st of April out if it. So all we have to do is to check if we get the date, we put in.

Requirements

None. Only JS itself.

Code

    function checkDate(year, month, day) {
        var d = new Date(year, month - 1, day);
        return d.getFullYear() == year && (d.getMonth() + 1) == month && d.getDate() == day;
    }

    checkDate(2016, 2, 28); // returns true
    checkDate(2016, 7, 35); // returns false

Amazon