Let’s Create Confused Meme Generate with Vanilla JS
The idea came into my mind suddenly and here you are looking at the screen “do we really need this?” This is just for fun for myself learning vanilla js around two weeks. I’ll talk about dom manipulation and how to create Element in JS.
First let’s create HTML. There’s a form with two input elements and two buttons. First text for the text we’ll put into butterfly and the second goes on. At the bottom we have an image with class named pic.
Now let’s move on CSS. (i’m very newbie so if i do something stupid just leave a comment. thanks. :) )
I’ll leave full code at the end but i want to talk about css position that we use for picture.
Let’s say we have a box and we want to put some text into it. We should add “absolute” position for the picture and “relative” position for the text items. So that we can move text elements. And these elements never leave the box.
We can finally talk about JS! Let’s give answers with questions.
How to access an element from JS?
const p = document.querySelector(“p”);
document is the whole html page and we’ll select each item by using querySelector. Also there are other methods too. So by selecting p; we select the first p elements and stored as p.
const pwithClass = document.querySelector(“.titleOfItem”);
Now we see . at the start. That means we select the item with has titleOfItem class. But if we have multiple elements, it will only select the first one. If we want to select all, we use “querySelectorAll”
const pWithID = document.querySelector(“#mainTitle”);
Now we see # at the start. That means we select the item with has mainTitle id. There’s no multiple selection since every id should be unique for elements.
How to addEventListener for a button?
What is event first of all?
“things to happen.”
Scrolling, click, resize.. all of these are an event and using javascript we control them. Let’s say we have a button and when user click the button we alert “hello user!”
we see “e.preventDefault()” and that means if button has default action, cancel it. so we can apply our code.
And we pass two arguments. The first one is name of the event and the second one is arrow function which is special type for JS.
button.addEventListener(“click”, event => {
event.preventDefault();
How to create element in JS?
We can dynamically create element using JS. We’ll pass tag name like in the example “p” tag.
let p = document.createElement(“p”);
We can add or element, give id, class or change it’s content. it’s up to you actually.
let name = “Yağmur”;
p.innerHTML = name;
p.setAttribute(“id”, “userName”);
So i did to-do list, quiz-app and a very basic meme generator for two weeks of my Vanilla JS journey. I just wanted to share my experience in a fun way. I hope you enjoy while reading it! Since i’m a learner if there’s a more wisely for doing something, just tell me. Thank you.