Skip to content

Instantly share code, notes, and snippets.

@tkalve
Created January 26, 2023 08:20
Show Gist options
  • Save tkalve/25856bfc3af0b3686910d042e8684c44 to your computer and use it in GitHub Desktop.
Save tkalve/25856bfc3af0b3686910d042e8684c44 to your computer and use it in GitHub Desktop.
A bookmarklet to fetch a dad joke
javascript: (function() {
// set up XMLHttpRequest with onready handler
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// parse joke from response
var response = JSON.parse(xhr.responseText);
var joke = response.joke;
// add joke to clipboard
navigator.clipboard.writeText(joke);
// create html element to show feedback to user
const feedback = document.createElement('div');
feedback.textContent = 'Joke added to your clipboard: ' + joke;
feedback.style = 'background: #333366; color: white; font-size: 18px; padding: 1em; position: fixed; top: 0; width: 100%; z-index: 2147483647;';
// add element to current webpage
document.body.append(feedback);
// set a timer to hide feedback element after 3 seconds
setTimeout(() => {
feedback.remove();
}, 3000);
}
};
// Call icanhazdadjoke.com to get a joke
xhr.open("GET", "https://icanhazdadjoke.com/", true);
xhr.setRequestHeader('Accept', 'application/json');
xhr.send();
})()
// Copy the below code into a new bookmarklet to get it working
javascript:!function(){var e=new XMLHttpRequest;e.onreadystatechange=function(){if(4==e.readyState&&200==e.status){var t=JSON.parse(e.responseText).joke;navigator.clipboard.writeText(t);let o=document.createElement("div");o.textContent="Joke added to your clipboard: "+t,o.style="background: #333366; color: white; font-size: 18px; padding: 1em; position: fixed; top: 0; width: 100%; z-index: 2147483647;",document.body.append(o),setTimeout(()=>{o.remove()},3e3)}},e.open("GET","https://icanhazdadjoke.com/",!0),e.setRequestHeader("Accept","application/json"),e.send()}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment