Tag: frontend

Drag and drop

Modern browsers come shipped with a lot of nice features in order to support drag and dropping. With only little help of javascript a lot of great tools can be built. But there is one downside, if for example you wished to have a lot of metadata then you’ll have to do that all by yourself. Also not all browsers transfer the same things on a drop event. For example Opera adds a meta tag to the beginning. Also some browsers keep the style from the source by adding it inline. (the horror for most fronteers) In order to do simple drag and drop, also being able to keep source data but defenitely not the styling, I had to get rid of these things.

Let’s start at the beginning. There are a few events that are used in drag and dropping. The drop event is used for, stating the obvious, dropping of the dragged content. The event handler contains the original dragged data in event.dataTransfer. This only works when you allow this property to be set. (assume jQuery, see code below) This dataTransfer contains the dragged data in several mimetypes. Almost always there are the ‘text/plain’ and ‘text/html’.

$.event.props.push('dataTransfer');
									

I know regex

I know regex

One of the most simple solutions is by just using the ‘text/plain’ type in order to print the dragged content. This would be awesome when there is only plain text, since one of the requirements is to show images and keep the datastructure available, this is not a good solution.

After a few other solutions I came up with replacing the content by nothing. This requires writing a regex that matches the entire <meta…> tag and also one that matches with all style=”…”.

// remove meta tag (everything that matches <meta >) (webkit)
draggedHtmlData = draggedHtmlData.replace(/<meta(.*?)>/g, '');
// strip styles (everything that matches style="*")
draggedHtmlData = draggedHtmlData.replace(/style="(.*?)"/g, '');
									

The outcome is quite clean html that respects the original structure and attributes but does not include meta-tags or strange style attributes.

Bonus: creating tag list 
Assume the following html:

<div contenteditable="true">
    <span contenteditable="false">one</span>
    <span contenteditable="false">two</span>
    <span contenteditable="false">three</span>
</div>
									


It basically states that you can type anywhere except in the current existing tags. The goal here is to create tags once one finishes typing. A tag consists of a word and in order to add some functionality and style there must be added a around it. An event will be triggered when a user leaves the area. Now there is one problem with the $.html() and $.text() because they either provide too much information or too less.

<div contenteditable="true">
    zero
    <span contenteditable="false">one</span>
    <span contenteditable="false">two</span>
    <span contenteditable="false">three</span>
   four
</div>

$('div').text() returns "zeroonetwothreefour"
$('div').html() returns "zero<span contenteditable="false">one</span><span contenteditable="false">two</span><span contenteditable="false">three</span>four"
									


This is an issue, the solution that I am currently using is get the $.html() and strip the from it by replacing them with a space. Next step is split the input on space and re-add the span tags.

var tags, length;
tags = $('div').html().replace(/<(.*?)>/g, ' ');
tags = tags.split(' ');
length = tags.length;
for (var i = 0; i < length; i = i+i) {
    $('div').append('<span contenteditable="false">' + tags[i] + '</span>');
}
									

The jQuery problem

$ is undefined
									

One of the most horrifying things that happened to me turned out to be a good lesson instead. Working on huge websites most of the time means that all kind of plugins, like jQuery, are provided by default. Also on my latest project, proactive chat, we were quite sure that the site uses jQuery.

quite sure jquery was loaded

Nevertheless we stumbled upon the error “$ is undefined”. The root cause of it was that the script we had was being executed before jQuery was loaded. Normally I would say, just include the script after jQuery has been initiated but in this case this was not possible.

Then I started thinking of a presentation I have been to by Remy Sharp, “I know jQuery. Now what?” He spoke about not using jQuery, and ever since the Mobilism event I have kept in mind that, at least for input fields:

$(this).val() === this.value
									

This inspired me to not see it as a problem but as a challenge to get rid of jQuery for this problem.

It turned out not to be very difficult since all we did was just getting a selector and kick off some functions. So this:

var selector = $('.ourSelector');
selector.on('change', function () {
    // do stuff
});
									


became this:

var selector = document.querySelector('.ourSelector');
selector.onchange  = function () {
    // do stuff
};
									

One thing Remy did is creating a substitute for the $ and on method. We decided not to, because that might have just leaded to other unforeseen problems with the rest of the site.

Frontend development and mobile security

Security is and always will be one of the biggest topics in web development. Now that the mobile web becomes bigger and bigger it has become even more important because most users do not have any protection installed on there mobile devices.

Of course there is a very clear reason why people do not install anti virus apps on a mobile device, the threat is simply not yet big enough and there has not been any news report on mobile viruses or malware. This is something we, frontend developers, need to have in mind when developing web applications.

Working with backend systems

One of the methods to prevent people from submitting unwanted data is to validate the entered data. Most often there is little frontend validation and the backend will perform the rest of the validations. But is that enough? Most frontend validations are just checking whether or not a field is required. But when the user gets asked to enter some kind of pre-formatted code, such as a Dutch postal code (1234 AB), it is not only safer but also more userfriendly when a user can only enter four digits and two alphabetic characters.

This also works the other way around. When retrieving data from a backend system you should not want to have to care about a customer that sees strange things on a website Especially not when you are a trusted organisation. Therefore it might be a good idea to validate the data provided by the backend. This can be achieved by using the same validators that are used to validate the input data from the frontend.

Conclusion

Mobile and security are getting more important these days for frontend development. The examples given are of course just simple examples to illustrate how frontend can help in improving a site security.

Datepicker headache

The jQueryui datepicker has been a pain in the ass for us the last few days. But with some research I managed to enter a date before 1970 as timestamp. These values are normally represented as negative timestamps. For yet an unknown reason the datepickers setDate function does not allow these values.

To solve this issue we simply create a new Date() from the timestamp to fill the setDate function. Now the datepicker does accept these values.

$date.datepicker('setDate', new Date(-4496400000));
									

iScout – Opening Ceremony 2.0

i, i, i all you hear is i. iPhone, iLife and now also iScout. iScout is a game for scouts where they have to solve puzzles and perform crazy exercises. Like last year we participated and I wanted to share one of the exercises we had to do.

The description was “Built a opening ceremony 2.0” and nerds as we are we immediately thought of a jQuery solution. So we started thinking and worked out a simple idea.

The HTML consists of just 2 div elements and 2 buttons, we could get the same result with one but for simplicity this was chosen.

<div id="mast"></div>
<div id="vlag"></div>
<button id="hijs">Hijs vlag!</button>
<button id="strijk">Strijk Vlag!</button>
​
									

The CSS, we used a gradient for the creation of a Dutch flag.

#mast {
    width: 10px;
    height: 200px;
    border:1px solid #000;
    border-radius: 5px;
}
#vlag {
    width: 100px;
    height: 50px;
    position: absolute;
    left: 10px;
    top: 150px;
    background: #ff0000; /* Old browsers */
    background: -moz-linear-gradient(top, #ff0000 0%, #ffffff 50%, #0000ff 100%); /* FF3.6+ */
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ff0000), color-stop(50%,#ffffff), color-stop(100%,#0000ff)); /* Chrome,Safari4+ */
    background: -webkit-linear-gradient(top, #ff0000 0%,#ffffff 50%,#0000ff 100%); /* Chrome10+,Safari5.1+ */
    background: -o-linear-gradient(top, #ff0000 0%,#ffffff 50%,#0000ff 100%); /* Opera 11.10+ */
    background: -ms-linear-gradient(top, #ff0000 0%,#ffffff 50%,#0000ff 100%); /* IE10+ */
    background: linear-gradient(top, #ff0000 0%,#ffffff 50%,#0000ff 100%); /* W3C */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ff0000', endColorstr='#0000ff',GradientType=0 ); /* IE6-9 */
}
​
									

And the jQuery for handling the required events.

$('#vlag').hide();
$('#strijk').hide();
$('#hijs').click(function() {
    $('#vlag').fadeIn().animate({
        "top": "5px"
    }, 3000);
    $('#hijs').fadeOut(function() {
        $('#strijk').fadeIn()
    });
});
$('#strijk').click(function() {
    $('#vlag').fadeIn().animate({
        "top": "150px"
    }, 3000).fadeOut();
    $('#strijk').fadeOut(function() {
        $('#hijs').fadeIn()
    });
});​
									

Check jsfiddle for the result.

Copyright © 2023 Kasper

Theme by Anders NorenUp ↑