-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
104 lines (80 loc) · 2.33 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
var search = "bdw c7";
var imgCount = 8;
var activeImage;
var score = 0;
$(document).ready(function() {
myApp.initialize();
});
myApp = {
initialize: function() {
this.getImages();
this.bindToSearchBox();
},
bindToSearchBox: function() {
var self = this;
$('#searchButton').click(function() {
var searchTerm = $('#searchField').val();
$('#main').empty();
self.getImages(searchTerm);
});
},
getImages: function(searchTerm) {
var self = this;
var searchQuery = searchTerm || search;
var url = "https://ajax.googleapis.com/ajax/services/search/images?q=" + searchQuery + "&v=1.0&callback=?&rsz=" + imgCount;
$.getJSON(url).done(
function(data){
var results = data.responseData.results;
self.parseImages(results);
self.parseImages(results);
self.randomizeImages();
self.bindToClickEvents();
});
},
randomizeImages: function() {
var $container = $('#main');
var elems = $container.children('.item');
elems.sort(function() { return (Math.round(Math.random())); });
$container.detach('.item');
for(var i=0; i < elems.length; i++) {
$container.append(elems[i]);
}
},
bindToClickEvents: function() {
$('.item').click(function() {
var $elClicked = $(this);
var flippedItems = $('.item.active').length;
$elClicked.addClass("active");
if ( flippedItems >= 1 ) {
var $key1 = $('.item.active').eq(0).data('index');
var $key2 = $('.item.active').eq(1).data('index');
if ($key1 == $key2 ) {
$('.item.active').addClass('matched');
myApp.updateScore();
}
setTimeout(function() {
$('.item.active').removeClass('active');
}, 800);
}
});
},
updateScore: function() {
score++;
$('#score').html(score);
},
parseImages: function(results) {
$.each(results, function(index, array) {
var img = results[index].unescapedUrl;
$('#main').append(
'<div data-index="' + index + '" class="item col-sm-4">' +
'<div class="flipper">' +
'<div class="front"><span>Front</span></div>'+
'<div class="back">' +
'<img class="img-responsive" src="'+ img +'"/>'+
'</div>' +
'</div>' +
'</div>'
);
});
}
};