Adding a div element dynamically in JavaScript using string concatenation (?)

While using the Google Maps API, I encountered a challenge with making a "card" appear instead of a tooltip or infobox when clicking on a marker. After following the guidance provided here, I was able to display the card. However, the method involved appending a large string containing hardcoded HTML for a white box with fixed information and links.

In an effort to enhance this functionality, I attempted to modify the code to dynamically insert desired information. By simplifying the card's content to just show a grey box upon marker click, you can view my progress here.

The crucial section of the code is:

google.maps.event.addDomListener(marker, 'click', function() {

    // Prevents card from being added more than once (e.g., during page resize)
    if ( $( ".place-card" ).length === 0 ) {

      var rootDiv = document.createElement('div');
      rootDiv.style = ('position', 'absolute');
      rootDiv.style = ('right', '0px');
      rootDiv.style = ('top', '0px');

      var secondDiv = document.createElement('div');
      secondDiv.style = ('margin', '10px');
      secondDiv.style = ('padding', '1px');
      secondDiv.style = ('-webkit-box-shadow', 'rgba(0, 0, 0, 0.298039) 0px 1px 4px -1px');
      secondDiv.style = ('box-shadow', 'rgba(0, 0, 0, 0.298039) 0px 1px 4px -1px');
      secondDiv.style = ('border-radius', '2px');
      secondDiv.style = ('background-color', 'white');
      secondDiv.style = ('width', '200px');
      secondDiv.style = ('height', '150px');


      rootDiv.appendChild(secondDiv);

      // Attempted methods to append the new div elements
      // $(".gm-style").append(rootDiv);
      // $(".gm-style").append('<div style="position: absolute; right: 0px; top: 0px;"><div style="margin: 10px; padding: 1px; -webkit-box-shadow: rgba(0, 0, 0, 0.298039) 0px 1px 4px -1px; box-shadow: rgba(0, 0, 0, 0.298039) 0px 1px 4px -1px; border-radius: 2px; background-color: white; width: 200px; height: 150px"></div></div>');
    }
  });

(My attempts to replace str2 with actual div elements have not been successful so far. Omitting the use of String() did not yield positive results either). Is there a more effective way to create and display this card rather than concatenating strings together?

Can someone clarify the purpose of $(".gm-style")? Although it seems to serve as an alternative to document.getElementById, my numerous efforts to find a suitable substitute resulted in errors since .gm-style represents a class name. Any insights would be appreciated.

Thank you!

Answer №1

Obtaining the HTML code for an element as a string is feasible, but it may not serve a practical purpose. When appending the string, it essentially duplicates the element.

The more effective approach is to simply append the existing element:

$(".gm-style").append(rootDiv);

Your method of setting styles appears to be incorrect. For instance, using ('position', 'absolute') results in assigning the string value 'absolute'. To apply styles correctly, utilize the properties of the style object like so:

var rootDiv = document.createElement('div');
rootDiv.style.position = 'absolute';
rootDiv.style.right = '0px';
rootDiv.style.top = '0px';

var secondDiv = document.createElement('div');
secondDiv.style.margin = '10px';
secondDiv.style.padding = '1px';
secondDiv.style.webkitBoxShadow = 'rgba(0, 0, 0, 0.298039) 0px 1px 4px -1px';
secondDiv.style.boxShadow = 'rgba(0, 0, 0, 0.298039) 0px 1px 4px -1px';
secondDiv.style.borderRadius = '2px';
secondDiv.style.backgroundColor = 'white';
secondDiv.style.width = '200px';
secondDiv.style.height = '150px';

Nonetheless, it is recommended to define CSS rules in a separate stylesheet rather than directly applying all styles to the element.

Answer №2

To transform an element into a string, you can retrieve its outerHTML.

$(".map-styles").append(mainDiv.outerHTML);

By the way, if you are utilizing jQuery, there is no need to append it as a string. Simply use

$(".map-styles").append(mainDiv);

and it will function correctly.

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

Trying to assign marker image dynamically through various database inquiries

With the use of the Google Maps API v3, I am currently displaying a map of the United States with markers placed at specific locations obtained from address queries in my Postgres database. My goal is to customize the marker image based on the result of ea ...

Unable to view through transparent merged geometry in three.js

Could someone assist me in understanding why, when merging the geometries of these boxes, I am encountering visibility issues from certain angles? Blue boxes represent normal individual boxes, while Orange boxes are the result of merged geometries. I am u ...

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 ...

Show only the present y-coordinate in the ToolTip of a chart.js

I am currently working on developing a chart using Chart.js, and my goal is to only show the y-axis value in the tooltip. The current display shows: date name_of_line: measurement example: Jan 1, 2020, 8:00:00 AM 5th Percentile: 100 oz. However, I would ...

Creating an intricate table layout using AngularJS and the ngRepeat directive

I'm attempting to create a table similar to the one shown in the image below using HTML5. https://i.sstatic.net/DiPaa.png In this table, there is a multi-dimensional matrix with Class A and Class B highlighted in yellow. Each class has three modes ( ...

Using Vue.js to display svg content inside the <svg> element

One of my Vue.js components is responsible for dynamically building the content of an svg element. Let's simplify things and say that the content consists of a <circle cx="50" cy="50" r="60" /> This component achieves this by manipulating a dat ...

What is the best way to ensure webpacker compiled javascript only runs once the page has finished loading in a rails application

What is the best location to place window.onload for it to execute on every page within a Rails 6 application? ...

A guide to resizing a canvas correctly in React with the help of p5.js

Currently, I am working on a project that involves resizing the model in the canvas when the canvas or window is resized. I have consulted the documentation for resizeCanvas() and implemented it. To achieve this, I first determine the ratio by dividing th ...

Exploring PHP Array for JSON Object Access

I'm currently working on a project where JavaScript is sending a POST request to a PHP controller. Here's the snippet of JS code in question: $.ajax({ url: 'map-controller/coordcontroller.php', data: {myData: JSON.stringify(myArray ...

Is there a method in JavaScript to locate a user's profile picture on Discord messages?

Is there a way to retrieve someone's profile picture on Discord using a JavaScript bot? ...

Pictures are automatically adjusted to a resolution of 0 x 0 within the Heroku application

I have encountered an issue with my simple webpage hosted on Heroku. Despite appearing perfectly fine on localhost, 4 images are automatically resized to 0x0 when viewed on Heroku. I am struggling to identify the cause of this problem. Here is how it appe ...

I am facing an issue with uploading files to my designated directory through Node.js Multer

After creating a web service using node js and implementing a form with React interface that includes user information and file upload, I encountered an issue while attempting to save the file to the specified directory on the node js server using multer. ...

Using AngularJS to send a model to ui-select

Here is the scenario at hand: A form includes a directive known as <timeZone ng-model="formModel.timeZone" This directive communicates with a web service to fetch timezone information The directive then presents the timezones in a ui-select dropdown ...

FCM onMessage event fails to activate

After extensively searching through numerous posts, I have been unsuccessful in achieving my goal with version 9.6.1 I receive a notification on my Windows notification bar. My objective is to log the message in the console and then take action based on i ...

Unintended redirects are occurring with AJAX requests when using the send() method

After loading the web page, I utilize AJAX to populate a list asynchronously. However, when the AJAX request is sent to retrieve data for the list box, instead of receiving JSON data as expected, an unintended web page containing the list box is returned. ...

When using the POST method with npm http-server, an error 405 is thrown

I'm attempting to send an Ajax request to execute a php file on a local http server. However, the browser console shows Error 405: method not allowed. Even after trying solutions from similar questions and enabling CORS on the http-server, I still ca ...

Troubleshooting EJS Relative Path Problem when Using "include" in an HTML Document

I'm encountering an issue with my "index.ejs" file... The current content of the ejs file: <!DOCTYPE html> <html lang="en" dir="ltr"> <!-- THIS SECTION IS FOR <head> TAG THAT WILL BE STORED INSIDE "so_ ...

Object array containing function objects

I'm currently working on implementing a model in JavaScript in an object-oriented manner. I have an object X that contains several functions, and I would like to create an object array "in X" where some of its fields reference functions within X. Here ...

Establishing a pixel width for a cell within a table

I've encountered an issue where setting a width to a div with the display: table-cell property is not working as expected. Here is my code: <header class="header layers"> <div class="wrap"> <h1 i ...

Why won't my HTML/CSS/JavaScript modal pop up in front of everything else?

Attempting to create my own modal in JSFiddle has been an interesting challenge for me. Once I had something that worked, I tried implementing it on my website. Unfortunately, the modal appears behind other elements on the page. What could be causing this ...