Skip to content

Instantly share code, notes, and snippets.

@harrisonmalone
Last active November 18, 2018 12:46
Show Gist options
  • Save harrisonmalone/423b454481508f6378e6e8d1408dbf0e to your computer and use it in GitHub Desktop.
Save harrisonmalone/423b454481508f6378e6e8d1408dbf0e to your computer and use it in GitHub Desktop.
using XMLHttpRequest objects to append chuck norris jokes to html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>AJAX</title>
<link rel="stylesheet" href="style.css">
<script defer src="script.js"></script>
</head>
<body>
<h1 id="joke">Click below to get chuck norris joke</h1>
<button class="btn btn-primary">Button</button>
</body>
</html>
const jokeBtn = document.querySelector('.btn')
const h1 = document.querySelector('#joke')
jokeBtn.addEventListener('click', randomJoke)
function randomJoke() {
const url = 'https://api.chucknorris.io/jokes/random'
const ajax = new XMLHttpRequest();
ajax.open('GET', url)
ajax.onreadystatechange = function() {
if (ajax.readyState === 4 && ajax.status === 200) {
const responseText = JSON.parse(ajax.responseText)
debugger;
const joke = responseText.value
h1.innerText = joke
}
}
ajax.send();
}
body {
max-width: 700px;
margin: 0 auto;
}
h1 {
font-family: sans-serif;
}
.btn {
display:inline-block;
font-weight:400;
text-align:center;
white-space:nowrap;
vertical-align:middle;
user-select:none;
border:1px solid transparent;
padding:.375rem .75rem;
font-size:1rem;
line-height:1.5;
border-radius:.25rem;
transition:color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out
}
.btn-primary {
color:#fff;
background-color:#007bff;
border-color:#007bff
}
.btn-primary:hover {
color:#fff;
background-color:#0069d9;
border-color:#0062cc
}
.btn-primary.focus,.btn-primary:focus{
box-shadow:0 0 0 .2rem rgba(0,123,255,.5)
}
/*
button {
padding: 20px;
border-radius: 10px;
border: 1px solid black;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
button:hover {
opacity: 0.6;
} */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment