Manipulating text on an image without using canvas, using vanilla JavaScript

I've been working on a project to create a meme generator without using canvas, as part of my DOM manipulation practice in vanilla JavaScript. I'm facing challenges in adding text to the user-submitted pictures and need some guidance in achieving this.

Despite trying methods like innerText, innerHTML, and appendChild, I seem to encounter issues with either replacing the image or getting errors. My intuition tells me that I might have to use JavaScript to add the picture and CSS to style it, possibly by adding a class with classList.

console.log('Currentfile: memegenerator');
let img = document.getElementsByTagName('img');

addEventListener('submit', function(e) {
  e.preventDefault();

  let UIurl = document.getElementById('picurl');
  let memeToBe = UIurl.value;

  let img = document.createElement('img');
  img.setAttribute('src', memeToBe);
  img.setAttribute('class', 'meme');
  
  // Rest of the JavaScript code for handling image and text addition


// CSS styles for the meme generator interface
h1 {
  color: navy;
}

/* Remainder of CSS styles */

.container {
  position: relative;
  text-align: center;
}
<main class="main">
  <h1 class="center">MEME GENERATOR!</h1>
  <hr class="rounded" />
  <form action="#" class="form">
    <label for="text_top">Text Upper:</label>
    <input type="text" name="text_top" id="text_top" /><br />
    <label for="text_lower">Text Lower:</label>
    <input type="text" name="text_lower" id="text_lower" /><br />
    <label for="picturl">Picture:</label>
    <input type="url" name="picurl" id="picurl" /><br /><br /><br />
    <input class="button " type="submit" value="Add Meme:" /><br />
    <hr />
  </form>
  <div id="location"></div>
  <hr class="border_lower" />
  <p class="center"><small>Thanks for visiting!</small></p>
</main>

Answer №1

After tackling this challenge of displaying images without saving them, I managed to get it up and running successfully.

The key issue you were facing was that your focus appeared to be more on the JavaScript aspect and overlooking the CSS element.

There are various ways to place images behind text, with the two most common methods being:

  1. Setting the images as a background image on the parent element (such as a div) and then adding the text within that element
  2. Using CSS to position the text over the image using z-index to layer them effectively

In my resolution, I opted for method #2.

In addition to some code refinement, the primary actions I took include:

  1. I generated a div with a class name of meme
  2. I inserted the image into said div
  3. I separated the top and bottom text into their individual divs and attached them to the meme div
  4. With CSS, I positioned the top and bottom text above the image

Another point worth noting is, when it comes to adding eventListeners, unless essential, it's advisable to link them to a specific element rather than just the document (or defaulting to document if nothing is specified). Attaching an event listener to the document means every click will trigger it, while binding it to the element ensures only clicks on that particular element are processed.

console.log('Currentfile: memegenerator');
let img = document.getElementsByTagName('img');
let form = document.querySelector('form');

form.addEventListener('submit', function(e) {
      e.preventDefault();
      let meme = document.createElement("div");
      let top_text = document.createElement("div");
      let bottom_text = document.createElement("div");
      let img = document.createElement("img");
      
      let btn = document.createElement("button");
      btn.setAttribute("type","button");
      
      img.src = document.getElementById('picurl').value;
      top_text.classList.add("top_text");
      top_text.innerHTML = document.getElementById('text_top').value;
      
      bottom_text.classList.add("bottom_text");
      bottom_text.innerHTML = document.getElementById('text_lower').value;
      
      btn.innerHTML = "REMOVE";
      
      meme.classList.add("meme");
      meme.appendChild(top_text);
      meme.appendChild(bottom_text);
      meme.appendChild(img);
      meme.appendChild(btn);
      
      let memeLocation = document.getElementById('location');
      memeLocation.appendChild(meme);

      document.getElementById('picurl').value = "";
      document.getElementById('text_top').value = "";
      document.getElementById('text_lower').value = "";

      btn.addEventListener('click', function(e) {
          meme.remove();
      })
});
/* CSS Styles */
<HTML Code Goes Here>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting HTTP Issues in Angular 2

I am currently facing an issue with my Angular 2 project's Http functionality. I have defined it as a parameter in the constructor, but it keeps printing as undefined. Below is the snippet of code from my project: import 'rxjs/add/operator/toPro ...

Retrieving data from a div container on an active website

Imagine having a website similar to , where you want to automatically retrieve the time value every second and save it in a .txt file. Initially, I considered using OCR (optical character recognition) software for this task, but soon realized that relying ...

Loading images in advance with AJAX for enhanced AJAX performance

My website is structured in a sequential manner, where page1.html leads to page2.html and so on. I am looking to preload some images from the third page onto the second page. After searching, I came across this amazing code snippet: $.ajax({ url ...

Restrict the HTML date input to only allow selection of the current date

In my form, I have set an input type date that is restricted to today's date by using the min and max attributes with JavaScript. The issue is that users are still able to manually input a different date instead of selecting it from the calendar popup ...

Upon attempting to retrieve a package version, NPM responds with an error stating "bash command not found."

I recently set up my project with a package.json file that includes the nodemon package among others. When I run #npm list --depth 0 in the terminal, this is what I see: ├─┬ [email protected] However, when I try to check the version of nodemo ...

`How to perfectly place multiple text blocks and images using CSS`

Check out this screenshot to see the issue I'm facing: Here is the HTML code: <div class="parent_process"> <div class="first_process"><img src="images/exprimer-besoin-telephonie.png"/><span style="width:18%">You fi ...

Restricting the input field in jQuery to only accept the maximum value based on the

There are two input fields: discountType and discountAmount. My goal is to set restrictions based on the value of discountType: if it's percentage, the discountAmount input should only accept numbers between 0 and 100; if it's absolute, any numbe ...

Unveiling the secret to accessing properties using v-if within a custom component template relocation

I'm currently working on an application that reveals a hidden div when the text "Create Test" is clicked. Everything works well when the code isn't placed inside the template of a component. This seems strange to me, what could be causing this is ...

Interact with JSON data in HTML without the need for PHP by using read and write

I have managed to successfully execute this code using PHP. However, I am now looking to achieve the same functionality without relying on PHP. My main objective is to be able to modify the value of "sel" directly from a JSON file. Below are my PHP and JSO ...

Mastering the art of utilizing Angular Routing alongside CSS grid for seamless website navigation

My <app-root> layout is pretty straightforward: app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.compone ...

The controller in AngularJS does not accurately reflect changes made by toggling a checkbox

My query involves a checkbox. <input ng-model="defaultAssigneeCheckbox" type="checkbox"/> <p>{{defaultAssigneeCheckbox}}</p> <button type="submit">Save</button> The paragraph underneath accurately displays and updates the c ...

Parsing JSON data on the client side in an ASP.NET application

I am currently working with JSON data that looks like this: "Table":[ { "AF":2000.00 "RegionNumber":1 "RegionName":"Black Sea" }, { "AF":100.00 "RegionNumber":1 "RegionName":"Black Sea" }, { "AF":15000.00 "RegionNumber":2 "RegionName":"Ista ...

Exploring Database with NodeJS, Express, and HTML

My goal is to create a basic web application using node.js where users can input data into a search bar and have that input sent to the server for database query. While I've successfully set up and connected my database, here's a glimpse of my co ...

Is there a way to align the height of a standard column with the ng-include section to ensure a cohesive page display?

I have been working on my Angular app and have implemented ng-include to dynamically add content to a template within the page. The issue I'm facing is that this specific area ends up being longer than both the html and body elements where it resides. ...

The privateroute is throwing an error because it cannot access the property state since

I stumbled upon a tutorial online detailing how to construct a customized private route, but alas, I am encountering an error. Upon execution, I am faced with the dreaded message: "Cannot read property 'state' of undefined" on line 12. As someon ...

A scenario in a Jasmine test where a function is invoked within an if statement

My coding dilemma involves a function: function retrieveNames() { var identifiers = []; var verifyAttribute = function (array, attr, value) { for (var i = 0; i < array.length; i++) { if (array[i][attr] === va ...

Why is it that Vue router beforeEach errors fail to throw exceptions when executing in the V8Js environment?

Working on a Laravel / Vue app with SSR, I encountered a bug in my code where I was trying to check user.id when the user object was null. If this had been running client side, fixing it would have been easy as the error would show up in the console. Unfo ...

The rotation feature for legends in Highcharts does not function properly on Internet Explorer 10 and 11 if the document mode is

When using Internet Explorer 10 or 11, rotation works perfectly fine if we select edge mode, as shown in the image. This information was taken from the High Chart Demo Charts. However, if we select Document mode 8 in IE 10 or IE 11, the rotation does not ...

Three.js: Buffer geometry does not provide any performance improvement

After examining the Three.js example found at webgl_performance, I decided to try improving performance by converting the model into a buffer geometry using the following code: var buffer = THREE.BufferGeometryUtils.fromGeometry( geometry ); Despite my e ...

Can you guide me on setting a background image URL for rails using javascript?

Within my Rails application, I have a collection of content paired with image buttons (each piece of content has an associated image). When a user clicks on one of these buttons, my goal is to display the corresponding image. All of my images are stored u ...