-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathindex.html
76 lines (65 loc) · 2.26 KB
/
index.html
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
<html>
<head>
<title>Firebase Chat Example</title>
<script src="https://cdn.firebase.com/js/client/2.0.2/firebase.js"></script>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<link rel="stylesheet" href="css/main.css"></link>
</head>
<body>
<div id="stream">
<h1>Firebase Chat</h1>
<input type="text" id="msgInput" placeholder="Your Message..."/>
<button type="submit" id="tweet-submit">Submit</button>
<div id="msg-box"></div>
</div>
<div id="here">
<h1>Who's here?!<a href="#" id="login"><img src="twitter.png"/>Sign in With Twitter</a></h1>
</div>
<script>
//STEP 1
var ref = new Firebase("https://<YOUR-FIREASE-NAME>.firebaseio.com/");
var messagesRef = ref.child('messages');
var usersRef = ref.child('users');
var currentUser = null;
//STEP 2
$('#login').on("click", function () {
authenticate();
});
//STEP 3
var authenticate = function() {
usersRef.authWithOAuthPopup('twitter', function (error, user) {
if (error) {
console.log(error);
} else if (user) {
usersRef.child(user.uid).set({username: user.twitter.username, pic: user.twitter.cachedUserProfile.profile_image_url_https});
}
});
};
//Save user's auth state
usersRef.onAuth(function (user) {
currentUser = user;
});
//STEP 4: Display a list of users who have logged in
usersRef.on('child_added', function (snapshot) {
var user = snapshot.val();
$("<div id='user'><img src=" + user.pic + "/><span id='username'>@" + user.username + "</span></div>").appendTo($('#here'));
});
//STEP 5: Store messages in Firebase
$('#tweet-submit').on('click', function () {
if (currentUser !== null) {
var message = $('#msgInput').val();
//Send the message to Firebase
messagesRef.push({user: currentUser.uid, username: currentUser.twitter.username, message: message, published: new Date().getTime()});
$('#msgInput').val('');
} else {
alert('You must login with Twitter to post!');
}
});
//STEP 6: Add messages to DOM in realtime
messagesRef.orderByChild("published").on('child_added', function (snapshot) {
var message = snapshot.val();
$('#msg-box').prepend($("<div class='msg-text'>").text(message.username).append('<br/>').append($('<span/>').text(message.message)));
});
</script>
</body>
</html>