DEV Community

Cover image for JavaScript Hearts: Input a user Message
Chris Jarvis
Chris Jarvis

Posted on

JavaScript Hearts: Input a user Message

Remember those Valentine's Candy Conversation hearts? For this project I'm recreating them using vanilla JavaScript and CSS.
Last year I added pre-made messages from a list. This time I'll show how to use user input to create a message.

I'll use the same CSS heart from the original post. I'll changed the background to purple on the user input version.

Draw a heart

If we're going to write on a heart we need to build the heart first. This is made with some basic shapes, a square and two circles. To make a CSS Circle you make a square and give it a border radius of 50%.

I added borders so you can see the individual shapes.

A heart made to two overlapping circles on a square that rotated 45 degrees.

/* The circles */
.bigheart:before, .bigheart:after {
    position: absolute;
    background-color: var(--heart-red);
    width: 400px;
    height: 400px;
    content: '';
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    -o-border-radius: 50%;
    border-radius: 50%;
}

/* moving the circles */
.bigheart:before {
    bottom: 0;
    left: -200;
}

.bigheart:after {
    top: -200px;
    right: 0;
}

/*Rotate the whole thing */

.bigheart {
    -webkit-transform: rotate(45deg);
    -moz-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    -o-transform: rotate(45deg);
    transform: rotate(45deg);
}

Enter fullscreen mode Exit fullscreen mode

Once the shapes are made, transform: rotate(45deg) turns the heart so the point is straight down. A drop shadow is added to make the heart standout from the background.

heart on purple background. Next to it is a box that says enter messages.

The Messages

I used an input box for a user to enter a message. It appears on screen as a user types. The ID of heart is targeted using getElementById.

<div class="login-screen">
<h1>"Hello There!"</h1>
<input placeholder="Enter a message." name="message" />
</div>

.
.
.
<!-- Messages displays Here -->
<div class="quote-screen" id="heart">

Enter fullscreen mode Exit fullscreen mode
const input = document.querySelector('input');
const enteredInput = document.getElementById('heart');

input.addEventListener('input', userMessage);

function userMessage(e) {
  enteredInput.textContent = e.target.value;
}

Enter fullscreen mode Exit fullscreen mode

Heart with text "git commit myself to you"

Wrap-up

This was silly and not practical. The biggest problem I had was I forgot to add display to the heart CSS. So the text was not on screen.

Top comments (0)