Nordic.js > Day 2

Like all the good things, Nordic.js also came to an end – for now. Just like yesterday, I am going to write down the parts that fully got my attention during the day.

Claudia Hernandez: JS in Wonderland

This presentation made most people see a side of javascript that never thought before. Claudia Hernandez introduced the web-page JSFuck and before that, she showed us a js expression similar to the one below:

![]

When you give the above characters to your js console, what do you think the result will be? Let’s read it from right to left.

  1. [] represents an empty array.
  2. If you negate an empty array which is received as a true value by exclamation mark, the result will be false.

So, can you guess the value true? It shouldn’t be hard to guess:

!![] = true
!![] = true
As you may already guess, JSFuck approach abuses the quirks in javascript. In a more positive way, we may call this approach as the art of javascript coding by using only non-alphanumerical characters.

In the beginning of Hernandez’ presentation, all the effort looked like some meaningless puzzle game – and I guess that is also what she wants the audience to think in the early minutes of her presentation. But, this technique actually led to the discovery of a serious hack. Here is a quote from the talk:

jsfuck hack storks nest sercan leylek hernandez

So, some people actually managed to inject some javascript code by using JSFuck way of programming. That was unexpected! And Hernandez perfectly underlines the whole idea with her remarkable ending.

That’s the point about the science. We should keep on discovering by pushing the limits even though there is no practical use in short run.

And another valuable quote from her presentation:

if hemingway wrote javascript

Feross Aboukhadijeh: P2P

Here is another hard-to-forget presentation from this year’s Nordic.js. I think Feross Aboukhadijeh presented the most interactive speech of the conference with his talk about Internet’s itself and P2P technology. He firstly shared a quite clear view of what attributes should internet possess:

  1. Resilient
  2. No middlemen
  3. Diverse
  4. People Powered

But, is it really resilient, diverse and etc?

Feross Aboukhadijeh p2p nordicjs

Feross shows that utopian internet model and modern reality do not really map. Internet is built to be a communication system to help its peers find an alternative way at the times of unavailabilities, but service giants stand in the centre of peers.

  • If they fail, we all fail. (Resilience?)
  • If they decide to halt a service, we have no right to speak up. (No middlemen?)
  • If they are blocked in some country, we are also blocked. (Diverse & People Powered. I’d like to remind you that Wikipedia is still blocked in Turkey.)

I felt huge sympathy for the thoughts of Feross, because that is some idea that I’ve been working on for some time via my product Reservation.no which recently declared war to the giants in table booking system.

Feross also caused us see that URL is actually a bad thing ūüôā

The L letter in URL stands for location. And if what you are looking for isn’t there, you will simply get a 404 error, although it is somewhere in the web.

That makes me think: Could or should URL be replaced in the future?

Ben Schwarz: Beyond the bubble

One cannot always give compliments to an event, right? Otherwise, there would be no point to improve things. The presentation of Ben Schwarz, ‘Beyond the bubble’, of course handled a critical accessibility issue. The founder of calibreapp, tutored us about the performance issues caused by the ignorance of developers and his stats also represented the status of internet accessibility for the majority of the world. However, most of these points were actually described with a more informative tone by Scott Jehl in Responsible Responsive Design¬†(Chapter 4: Delivering Responsibly).

Despite my critical views, ‘Beyond the bubble’ still hits the target. The participants of the event will be more careful when they include their CSS/JS files from now on and many of them will behave more professionally at performance testing.

Final Comments

I regret that I am not able to mention the other speakers’ hard work, but I am sure that some other blogger/developer is writing about them. Big thanks to all speakers!

Also, I have a feeling that the second day of Nordic.js was more fun. Maybe that was because of the distributed performances of the hosts,¬†Unn¬†Swanstr√∂m & Mattias P. Johansson. (Like live tattoo show, video call, etc…)

And, special thanks to the conference organisers: Jonny Strömberg, Martina Elm and Johannes Edelstam.

Screen Shot 2017-09-08 at 23.57.28

See you all next year!

Sercan Leylek / Stockholm

Advertisements

Nordic.js > Day 1

Hello from Nordic.js,

I am happy to write from one of the most important web-development conferences in Scandinavia. The event takes places in Stockholm this year and the first day is already over. Most people join this conference with their colleagues and we should surely say that the organisation is quite international. For those, who has no idea about what Nordic.js is, I copied down some intro-text from event’s official website:

Nordic.js is a two-day conference all about JavaScript. We want to inspire and to get inspired, to meet and learn from others and to bring our community closer together.

And here is a picture from the opening session!

nordicjs sercan leylek opening

One of the most important metrics to measure the quality of a conference is to see how much you are able to remember after the event. So, I list down some of the memorable experiences that I got here on my first day.

Sacha Greif’s Survey: The State of Javascript

The State of Javascript is an online survey performed by the creator of VulcanJS, Sacha Greif. His survey aims to see the changing trends of JavaScript libraries. The survey checks which libraries become more popular among the developers and also monitors those which do not promise a bright future.

Sacha Greif publicly shared the 2017 survey results for the first time at Nordic.js event and one of the results there particularly caught my attention. We recently started a training program on Angular, but his survey indicates that Vue.js library makes a visible move into Angular’s territory. People migrate from Angular to Vue.js because of complexity issues.

Tomasz Ducin’s Advice on Asynchronous Calls

Ducin‘s session had additional importance for me and my colleagues, because we got a lot to do with asynchronous calls on one of our major products. He mentioned the critical differences between the functions such as .all(…), .race(…), .any(…), .some(…).

And Ducin’s advice at the end of his speech is worth to remember:

For a single async operation, a promise is enough.

For a combination of different operations – use async await.

But if something is repetitive – make it an observable stream.

tomasz ducin nordicjs sercan leylek asynchronous

Sacha Greif and Tomasz Ducin were the first two speakers of the event and I met them both during the day for my questions. Luckily, Jesse Rosenberg (core developer on MeteorJs) joined our conversations, too. We all use some open-source libraries and I am sure very few of us donate to the creators and contributors. I asked them how a common library developer makes money. Tomasz Ducin said that creating a popular JavaScript library provides quite serious recognition and hence, one can work as a consultant for other companies.

Fast Track

I’d rather listing some of the other important experiences and information that I got today:

  • I’d like to heartily congratulate Nordic.js organisers for helping us meet Leonie Watson who helped us think and care more about accessibility issues of blind users. Thanks to her speech Accessibilty Object Model is in my to-study list now.
  • Rachel Andrew‘s presentation on CSS/Grid issues made me write down a lot of notes. Learning that fr unit may replace percentage in width/height¬†attribute was a privilege. And here is a quote from her speech: ‘Feature queries will be your new best friend’.

rachel andrew stockholm nordicjs sercan leylek css

  • I didn’t know that Javascript was actually built by a committee called ECMA International and any developer could take a part in testing (See: Test262). A big thanks to Myles Borins. Every minute of his presentation got my focus.

Summary of the day

The first day was full of ideas, networking and information exchange. The organisation is neat and things happen timely. I am definitely not impressed by the food, but that was expected ūüôā

Sercan Leylek / Stockholm

Object doesn’t support property or method ‘foreach’

I came across with this error while performing some cross-browser tests after my recent implementation. I noticed that forEach javascript function works well on popular browsers like Chrome and Mozilla Firefox, but it fails on Internet Explorer. Hence, you eventually face with the following error:¬†Object doesn’t support property or method ‘foreach’.

Therefore, I replaced the forEach usage with $.each(…). See some sample below:

Code failing on IE & Edge

document.querySelectorAll('#slideInContent h2').forEach(function(h2) {
...
});

Successful translation

var h2_elements = document.querySelectorAll('#slideInContent h2');
$.each(h2_elements, function(i, h2) {
...
});

Sercan Leylek / OSLO

Drop File out of the box issue

Certainly, there are many file upload tutorials around the web, but I noticed a small issue on these examples. While I was working on the implementation of my file upload (Drag & Drop) case, I struggled with drop out of box issue. Of course, there are many ways to tackle this¬†problem –depending on your technology set-, so I will cover¬†the basic understanding of the solution.¬†But, before doing that, we’d better clearly explain what I mean by ‘drop out of the box issue’.

Definition of the bug

The gif below is a fine illustration of expected user behaviour on drag & drop operations, but what if the user drops the file outside of the predefined box?

drag-drop-upload out of box issue
Source: https://css-tricks.com/drag-and-drop-file-

If this exception is not handled, your browser will basically show the dropped picture from your local and the browser will point to the address of your file in its local address.

file drag and drop out of box issue

Solution!

The reason is simple: As you might already know, you should be using preventDefault() and stopPropagation() methods in Javascript. Screen Shot 2017-05-19 at 21.12.42

And expectedly, you will remove/add some CSS class as the user hovers over and out of the dropbox (dashed area). So, if you limit your event target only for the dropbox, outside of the dropbox area will not trigger preventDefault() and stopPropagation() methods. And hence, when you drop the file outside of the box, the rest of the page will act upon the default behaviour. As a result of these inputs, we need to follow two basic points for our solution:

  1. Make sure that your event handle does not only handle the dashed area (dropbox)
  2. Use hover CSS to figure out if the file is dropped into the correct place
Screen Shot 2017-05-19 at 21.26.05
Key line for the solution

Highlighted code line above does the check mentioned in the 2nd statement above. This piece of code runs when the drop event is triggered. And the translation is as follows:

If the dropped area does not have “is-dragover” class, do nothing!

Last Word

Drop out of box bug is definitely the result of a negative testing approach. If you do not handle this exception, your interface will still work but we do not want barely working product. This bug fix will increase the quality of your file upload interface and increase user satisfaction.

Sercan Leylek / OSLO

Using json_array_elements() on Postgres

I noticed that there are very few examples of Postgres¬†json_array_elements() and hence, we have this small post published. While writing queries for JSON data field, I’d recommend you to use an online JSON viewer website like¬†jsonviewer.stack.hu. This tool will help you see the structure of the content that you are working on. See the example below:

raw-json
Raw Json Data
json-structure-view
Structured Json Content

As you see above, json content can be represented in various object structures. We can see the content as object value or as array content. Certainly, we need different methods to be able to query array and object structures. Before showing the first SQL, let us underline a few assumptions:

  • Database table name: publications
  • Json data column name: properties
  • And consider that publications table contains only one raw – which is above.

Now, let’s see this simple query:

SELECT properties->>’sortOption’ FROM publications;

Query above will return “subjectArena” value. Why? Because, we are referencing the values labeled via “sortOption” tag and since we have only one row in our table, “subjectArena” string value will be returned by the query. And yes, you should be careful with the syntax. ‘->>’ command is used for string reference, and the tag name should be stated between¬†apostrophe characters. (properties->>’sortOption’)

sortOption and publisherTermsAccepted tags are part of the object structure, but how about the availableOrganizations section? This is an array structure and you cannot access this query via simple referencing. Therefore, we should use json_array_elements() function.

SELECT json_array_elements(properties->’availableOrganizations’) FROM¬†publications;

And this query will return the following values:

123

456

789

As you might have already noticed, we refer to the array (availableOrganizations) via ‘->’¬†command. This command is used for object pointing, as ‘->>’ is used for string reference. See the document here for more operators:¬†www.postgresql.org/docs/9.3/static/functions-json.html

Sercan Leylek / OSLO

Using AdminLTE Calendar Component

AdminLTE is a great template for online admin panel systems and the template provides a huge range of needs. See the template here: almsaeedstudio.com

Among other handy components, AdminLTE provides the following calendar box.

adminlte-calendar-jquery

Of course, when the user clicks a date, there should be a way to pick this content. I looked around the web if somebody else already blogged about the same problem, but saw none. After quite thorough html source investigations, I realised that AdminLTE uses datepicker-switch class in table headers (<th>). So, the issue was solved for me. The rest is jquery code and call to the related php files.

/*
The following function is triggered when a calendar day
is clicked by the user. Corresponding box item (Agenda)
will show all reservations for the specified date and it
should also update the Capacity value under the calendar box.
*/
$(document).on('click', 'td.day', function() {
var month_and_year = $("th.datepicker-switch").html();
var day = $(this).text();
var picked_date = day + ' ' + month_and_year;
var myData = 'picked_date=' + picked_date;

jQuery.ajax({
type: "POST",
url: "./backend_php/reservation/list_reservations_of_active_date.php",
dataType:"text",
data:myData,
success:function(response){
$("#todays_agenda_content").html(response);
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});

jQuery.ajax({
type: "POST",
url: "./backend_php/reservation/update_capacity.php",
dataType:"text",
data:myData,
success:function(response){
$("#progress_bar_respond").html(response);
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
});

 

Sercan Leylek / OSLO

Se Aftenposten i dag :)

‚Äď Foreldrene holder barna tilbake

Sercan Leylek (29) fra Tyrkia er blant dem som ble k√•ret p√• Topp 10-listen til Leadership Foundation i fjor h√łst over innvandrere som er forbilder for andre fordi de har gjort det skarpt p√• sine omr√•der.

Han kom til Norge som 22-√•ring, ferdig utdannet som webutvikler og software-ingeni√łr. Etter tre m√•neder som trainee, fikk han fast jobb i et Oslo-basert firma.

Leylek er aktiv samfunnsdebattant, forfatter, engasjert i innvandrersp√łrsm√•l og holder kontakt med det tyrkiske milj√łet i Oslo. Han nikker gjenkjennende til det unders√łkelsen viser.

‚Äď Dessverre er det nok s√•nn at en 15-√•ring som innvandrer med familien sin fra Tyrkia, vil ha kommet kortere i sin utvikling som 18-√•ring her i Norge enn hvis han var blitt boende i hjemlandet, sier han.

F√łler seg hjelpel√łse

‚Äď I Tyrkia skjer utviklingen raskere enn i innvandrermilj√łet her i landet. Her er foreldrene altfor opptatt av √• beskytte familiens tyrkiske identitet, og mange gir ikke barna nok motivasjon til √• ta utdannelse. De har for f√• ambisjoner p√• barnas vegne, mener han.

Han mener 90 prosent av barri√®rene innvandrerungdom m√łter, skyldes foreldre og bakgrunn ‚Äď bare ti prosent skyldes samfunnet.

Leylek ser at mange ten√•ringer som kommer hit, f√łler seg hjelpel√łse og gj√łr store anstrengelser for √• klare skolen.

‚Äď Da trenger de foreldre som gir dem en ¬ęboost¬Ľ, og ikke stopper dem, sier han.

http://www.aftenposten.no/norge/Tenaringsinnvandrere-klarer-seg-darligere-i-livet-enn-sine-smasosken-613175b.html

sercan-leylek-aftenposten-webutvikler-software-ingenior

JQuery – Textarea item returns ‘undefined’ value

I’ve just come over another time consuming and perfectly annoying issue, so I decided to drop this post.

My following jquery command was keep returning ‘undefined‘ value for no good reason.

JQuery part:

 var comment = $('textarea#' + telephone_nr).val();

HTML part:

<textarea id ="9801213">

As you guess, I used the telephone number value as my identifier to access the value in textarea item,¬†but although I tried a number of methods, I didn’t manage to get the correct value. Weirdly, the internet is full of wrong information for this error. Many sites claim that textarea item has no .val() function or value attribute. (<<< This is highly wrong info. Textarea item has .val() function. )

In about half an hour, I tried the following piece of code because of some adviser website:

var comment = $("textarea")[0].value;

The code above actually functioned (Pay attention! I didn’t say it worked, it only¬†functioned). Certainly, this is not a solution for me. Because I don’t want to access the textarea item in an array, I want to be able to access these values dynamically.

FINAL SOLUTION

After a few more attempts, I realised that the issue must be related to the id value. My project puts too much trust in telephone number value as primary key, and cause I created some other html items (like textbox, anchor, etc…), somehow I created a confusion while accessing the correct item. I still don’t know why this happened and I assure you there is only one textarea item with a unique identifier.

However, I solved the issue by altering the id attribute of my textarea items.

JQuery part:

var comment = $('textarea#tel_' + telephone_nr).val();

HTML part:

<textarea id ="tel_9801213">

Making sure that id value has a unique value worked. That’s it.

What’s next?

I actually encountered this issue while implementing my last work. I’ve been building a restaurant reservation system and textarea field will keep the comments of the restaurant manager for his/her clients.

restaurant_reservations_tool_sercan_leylek

I will most likely encounter more trouble while working on this product, and naturally, there will be more posts. Stay tuned!

Sercan Leylek / OSLO

Reflex Game with JQuery & PHP

Reflex Game (or Reaction Game in other words) is a popular online game to practice JQuery and other web development tools. Of course, you can find a number of samples online, but I decided to contribute my work in the web ocean as well.

We will start with the clear description of the task, because …

‚ÄúIf you can't write it down in English, you can't code it.‚ÄĚ ‚ÄĒ Peter Halpern
‚ÄúIf you can’t write it down in English, you can’t code it.‚ÄĚ ‚ÄĒ Peter Halpern

DESCRIPTION

Reflex Game will receive¬†the player’s name and will continue to pop up a square item on the page as long as the player clicks on the square items. Squares will show up with some random time and random location of the screen – of course, within a predefined area.

The purpose of the user is to click the square as early as possible. The game will continuously save the user name and the score (clicking time) into the database.

Top-10 best scores will be listed with user names and the scores. List should be synchronously or asynchronously updated on the same page.

Feel free to download complete project from my GitHub repository: https://github.com/sercanl/Reflex_Game

And you are welcome to put your name in my Top-10 list. Current best time is 0.318 seconds.

Play Reflex Game

TECHNOLOGIES

  • HTML, CSS
  • JQuery, JS
  • PHP, Mysql

INSTALL.PHP

To keep the records, a database and at least one table are certainly needed. Creating install.php file is quite handy both for debugging and carrying the project from localweb to production environment.

$db->select_db("reflex");
echo "Database <strong>Reflex</strong> created successfully!
";
echo "Creating the <strong>game_stats</strong> table...
";
$db->query("
CREATE TABLE game_stats
(
ID int AUTO_INCREMENT PRIMARY KEY,
user_name VARCHAR(20),
reflex_time DOUBLE
);
");
echo "Table game_state is created. Ready to <a href=\"play.php\">play</a> the game!
";
$db->close();

Play.php

This will be the interface of the user. The page is divided into 3 main sections:

  • User Name Interface
  • Game Area
  • Hi-Score Table

User Name Interface

This interface will let the player type the user name. See the html code below:

<h1>Current User</h1>
<input type="text" name="current_user" id="current_user" value="Anonymous" maxlength="15">
<div id="textarea"></div>

And the javascript code below should be inserted into thesection of the page. We use keyup function to inform the client that current_user textbox should not be empty with the help of a javascript function (isBlank(str)).

<script type="text/javascript">
 $(document).ready(function(){
 refreshTable();
 $("input#current_user").keyup(function(){
 var text = $('input#current_user').val();
 if (isBlank(text))
 $("div#textarea").html("
Please enter a username");
 else
 $("div#textarea").html("");
 });
 });

 function isBlank(str) {
 return (!str || /^\s*$/.test(str));
 }

 function refreshTable(){
 $('#responds').load('getTable.php', function(){
 setTimeout(refreshTable, 1000);
 });
 }
</script>

Game Area

This section handles a more tricky part. The javascript code placed in theelement will continuously call the function createSquare() as the user clicks the random square.

document.getElementById("square").onclick = function() {
clickedTime = Date.now();
reflexTime = (clickedTime-createdTime)/1000;
document.getElementById("printReactionTime").innerHTML = "Your last score is <strong>" + reflexTime + "</strong> seconds";
this.style.display="none";
insertScore(reflexTime);
createSquare();
}

And the function createSquare will use Math.random() function to create random time and the coordinates for the square.

	function createSquare() {
		var time = Math.random() * 3000;

		setTimeout(function()
		{
			var y = Math.random() * 340;
			var x = Math.random() * 250;

			document.getElementById("square").style.top = y + "px";
			document.getElementById("square").style.left = x + "px";
			document.getElementById("square").style.display="block";
			createdTime = Date.now();
		}, time);
	}

Hi-Score Table

The section for Hi-Score list is as simple as it is. The label responds will serve here to receive the content created by getTable.php.

<td>
<h1>TOP-10</h1>
<div id="responds"></div></td>

And, there is one more important detail to call getTable.php for work. Thesection should contain the following javascript function to call for the update and the result should refer to the predefined lable (responds).

    function refreshTable(){
        $('#responds').load('getTable.php', function(){
           setTimeout(refreshTable, 1000);
        });
    }

Response.php

This module will do the backend work. The variables current_user and reflexTime will be posted into Response.php and the php code will insert these records into the database.
if(isset($_POST["current_user"]) && strlen($_POST["current_user"])>0)
{
 $reflexTime = $_POST["reflexTime"];
 $current_user = $_POST["current_user"];
 $insert_row = $db->query("INSERT INTO game_stats(user_name, reflex_time) VALUES('".$current_user."', $reflexTime)");

 if($insert_row)
 {
  $db->close();
 }
 else
 {
  header('HTTP/1.1 500 Looks like mysql error, could not insert record!');
  exit();
 }
}
Since we do not wish to keep the scores of an unnamed user, INSERT query is not initiated when the current_user varilable is empty.

getTable.php

The code snippet below will show us the early mentioned Hi-Score listing. SELECT query simply limits the top 10 shortest reflex time and therefore, LIMIT keyword is used in mysql.
<?php include("include/connect.php"); $results = $db->query("
SELECT user_name, reflex_time
FROM game_stats WHERE 1
ORDER BY reflex_time ASC LIMIT 10");
$i = 1;
echo "
<table>";
while ($row = $results->fetch_assoc())
{
echo "
<tr>
<td>$i)</td>
<td>".$row["user_name"].'</td>
<td>'.$row["reflex_time"].'</td>
</tr>
';
$i++;
}
echo "</table>
";
$db->close();
?>

SOURCE CODE

Feel free to download complete project from my GitHub repository: https://github.com/sercanl/Reflex_Game

CONCLUSION

Reflex Game is a good practice tool to use PHP and Jquery together while implementing the front and back end of things. As you saw, our player will be only in touch with the page Play.Php.

You are welcome to put your name in my Top-10 list. Current best time is 0.318 seconds.

Play Reflex Game

Sercan Leylek / OSLO