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

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


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 This tool will help you see the structure of the content that you are working on. See the example below:

Raw Json Data
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:




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:

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:

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


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', '', 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;

type: "POST",
url: "./backend_php/reservation/list_reservations_of_active_date.php",
error:function (xhr, ajaxOptions, thrownError){

type: "POST",
url: "./backend_php/reservation/update_capacity.php",
error:function (xhr, ajaxOptions, 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.


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.


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.


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


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:

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

Play Reflex Game


  • JQuery, JS
  • PHP, Mysql


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.

echo "Database <strong>Reflex</strong> created successfully!
echo "Creating the <strong>game_stats</strong> table...
CREATE TABLE game_stats
user_name VARCHAR(20),
reflex_time DOUBLE
echo "Table game_state is created. Ready to <a href=\"play.php\">play</a> the game!


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">
 var text = $('input#current_user').val();
 if (isBlank(text))
Please enter a username");

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

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

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 =;
reflexTime = (clickedTime-createdTime)/1000;
document.getElementById("printReactionTime").innerHTML = "Your last score is <strong>" + reflexTime + "</strong> seconds";"none";

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;

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

			document.getElementById("square") = y + "px";
			document.getElementById("square").style.left = x + "px";
			createdTime =;
		}, 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.

<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);


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)");

  header('HTTP/1.1 500 Looks like mysql error, could not insert record!');
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.


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 "
while ($row = $results->fetch_assoc())
echo "
echo "</table>


Feel free to download complete project from my GitHub repository:


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 Launched Today!

Sercan Leylek introduces the website for SPIRE AS this week. Amela Koluder, one of the leading innovation experts in Norway, is the owner of SPIRE which means “to sprout” in Norwegian. SPIRE aims to provide mentoring and creative workshops for especially international organisations. SPIRE previously worked with H&M, Røde Kors, Favne, inmeta, and Heggelund & Koxvold.


The website not only holds content for innovation business, it also provides some competitiveness tutorial (translated as Konkurransekraft in Norwegian).

Mobile compatible website was developed by using HTML5, CSS. Some php scripting also provides the messaging functionality for the users and the site admin.