javascript Issue with styling when creating new elements

Today, I created a new function:

 function zoom(obj){
            var img = (!document.getElementById(obj))?false:document.getElementById(obj);
            var fullImage = (img.getAttribute("image") == null)?false:img.getAttribute("image");
            if(!fullImage || !img) { return false; }
            if(!document.getElementById("::img")) {
            var ob = "<div id='::img' style='position:absolute;top:300px;left:300px;width:200px;height:200px;-moz-border-radius:100px;border:1px solid #ddd;-moz-box-shadow: 0px 0px 8px #fff;display:none;'></div>";
            document.write(ob);}
            img.onmousemove = function(e) {
            var x = Math.floor(((e.pageX-7) - (img.offsetLeft - 8)) * 100 / img.width);
            var y = Math.floor(((e.pageY-7) - (img.offsetTop - 8)) * 100 / img.height);
            x = (x>100)?100:(x<0)?0:x;
            y = (y>100)?100:(y<0)?0:y;
            var ob = document.getElementById("::img");
            ob.style.background = "url('" + fullImage + "') no-repeat";
            ob.style.display = 'block';
            ob.style.backgroundPosition = x + '% ' + y + '%';
            ob.style.left = e.pageX + "px";
            ob.style.top = e.pageY + "px";
            }
            img.onmouseout = function() { document.getElementById("::img").style.display='none'; }
        }
  1. Instead of:

     var ob = `""`;
                document.write(ob);

    I attempted to use createElement() and appendChild() functions, but it didn't work. How can I make it work with createElement()?

  2. Is there a way to add all styles in one line using only JAVASCRIPT :

ob.style.background = "url('" + fullImage + "') no-repeat";
                ob.style.display = 'block';
                ob.style.backgroundPosition = x + '% ' + y + '%';
                ob.style.left = e.pageX + "px";
                ob.style.top = e.pageY + "px";

Preview: JsFiddle

Answer №1

Works perfectly:

let newElement = document.createElement('div');
newElement.id = "::img";
newElement.style.cssText = 'position:absolute;top:300px;left:300px;width:200px;height:200px;-moz-border-radius:100px;border:1px  solid #ddd;-moz-box-shadow: 0px 0px 8px  #fff;display:none;';

document.getElementById("divInsteadOfDocument.Write").appendChild(newElement);

You can also efficiently set the CSS properties in one go by using element.style.cssText.


I recommend using more descriptive variable names and avoiding reusing the same name for different elements. It appears that you are using obj for multiple elements (overwriting its value within the function), which could lead to confusion.

Answer №2

element.style.backgroundColor = "red";
element.style.fontSize = "2em";

Alternatively, you can directly write the element in HTML and set it with .innerHTML = [raw html code]... although this method is not recommended due to its poor aesthetics.

To address your initial inquiry, start by utilizing

var myElement = createElement(...);
, followed by
document.body.appendChild(myElement);
.

Answer №3

To add your new element to the current element in the DOM, make use of the appendChild function.

Answer №4

Many have already mentioned the use of appendChild.

If you call document.write() on a page that has already been loaded, it will first execute document.open() which will erase all existing content on the page (including the script trying to write). This is generally not recommended practice.

Answer №5

While searching for a solution to set the background image of a div, I stumbled upon this page. It turns out that I forgot to enclose the URL within the `url()` function when setting the `backgroundImage` attribute. The following code snippet worked perfectly for me:

for (var i=0; i<20; i++) {
  // Create a wrapper around an image element
  var wrapper = document.createElement('div');
  wrapper.className = 'image-cell';

  // Add the image element
  var img = document.createElement('div');
  img.className = 'image';
  img.style.backgroundImage = 'url(http://via.placeholder.com/350x150)';

  // Append the image to its container and add both to the body
  wrapper.appendChild(img);
  document.body.appendChild(wrapper);
}

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

Conceal content upon clicking with JavaScript

Showing a form after clicking a link can be achieved using this code: $(function () { $('.msg').on('click', function (e) { e.preventDefault(); $(this).next('.msgarea').show(); }); }); <a href="" cl ...

Transform the JSON data to generate a fresh JSON output

I'm seeking help to develop a script that generates JSON data based on specific conditions. As of now, I believe my logic is correct. Any assistance would be greatly appreciated. CURRENT ISSUES: [resolved]I am unable to determine why the duration ...

When you click on the column header to sort, the corresponding column row changes color in JavaScript

https://i.sstatic.net/4ELuv.jpg When a user clicks on a column to sort, the color of the column changes or highlights the row. In my tablesorter with ascending and descending sorting capabilities, I want the sorted column to change colors for better visib ...

How can I create a route using associations for /users/me in Sails.js?

My primary model is called Accounts. Additionally, I have several Has Many models such as Notifications and Friends Within my file named main.js, I would prefer to execute commands like: socket.get('/users/me/notifications'); instead of: soc ...

What is the most effective way to reset the v-model in the child component using the parent component?

Could you please assist me? I have been trying for 10 hours straight and it doesn't seem to work. What I am aiming for is that when I click on @click="cleanDataForm" in the Parent Component, the v-model text in the Child component will be emptied. I h ...

Switching video sources with jQuery and HTML5 can be achieved by clicking on an

I need to develop an engaging video using HTML5 and jQuery. My objective is to: Start playing video1 Show button1 when video1 finishes, then switch to video2 upon clicking and hide button1 Play video2 Display button 2 after video2 ends, then change to vi ...

Angular single page application with a sleek, user-friendly navigation bar for easy browsing

I have been attempting to solve the issue at hand without much success. As a newcomer to web development, I have been working on creating a basic app using angularjs and bootstrap. My pages are fairly sparse, consisting only of a few inputs and buttons t ...

Transferring attributes from parents to children

For some time now, I have been attempting to develop a Vue.js-based "customizable form template". The approach I envisioned involves: Developing a "custom-form" component that accepts a vueForm prop and displays a form. The vueForm prop is structured as ...

What is the best way to enhance a React Native component's properties with Flow?

I'm currently working with Flow version 0.54.1 in my React Native project, specifically using version 0.48.3. I have developed a component named PrimaryButton that acts as a wrapper for the native TouchableOpacity component. My goal is to define custo ...

Is there a way to animate without specifying a duration?

Exploring the capabilities of the Animated component in react-native, I came across the powerful Animated.timing(); function which operates within a specific duration defined as duration: 2000,. While duration is useful in certain scenarios, I found myself ...

What steps can be taken to access the body prior to uploading a file using multer?

In my current project, the administrators are able to upload MP3 files and input parameters such as the song name. I have chosen to utilize the multer middleware for managing multipart/form-data. The issue I am facing is that req.body.gender always retur ...

Filtering data in Vue.js using JSON specifications

How can I display only the names in the data? I currently have cards filtered by cities <div v-for="item in stationCityData"> <div v-for="option in filteredCity" style="background:#eee;padding: 20px"> <!-- <div v-for="option ...

Utilizing JavascriptExecutor in Selenium Webdriver to start playing a video

Is it possible to trigger the play function in a page's JavaScript jQuery code using JavascriptExecutor? Below is an example of code extracted from a website: <script type="text/javascript"> jQuery(document).ready(function($) { $('#wp_mep ...

Obtain picture from firebase utilizing react Js

I have attempted multiple methods to download images from Firebase, but the download URL is not functioning as expected. Instead of downloading the image directly, it opens in a new tab. The function used in Firebase: export async function addMedia(locati ...

Mongoose not functioning correctly when attempting to remove items from an array that meet a certain condition

In my document, I have a property called weeks which is an Array containing Objects. [ { "time": [ "06", "00" ], "active": false, "reason": " ...

Is the Typescript index signature limited to only working with the `any` type?

I recently made changes to my interface and class structure: export interface State { arr : any[]; } export const INITIAL_STATE: State = { arr: [] }; This updated code compiles without any issues. Now, I decided to modify the Interface to incl ...

Despite being listed in the entry components, HelloComponent is not actually included in the NgModule

Check out my StackBlitz demo where I am experimenting with dynamically instantiating the HelloComponent using the ReflexiveInjector. The HelloComponent is added to the app modules entryComponents array. Despite this setup, I am still encountering the foll ...

Create an instance using the window object in JavaScript

Having an issue when trying to instantiate a class using the window object. I have a namespace called UTIL and within it, there is a class defined as follows: var UTIL = { Classes : {}}; UTIL.Classes.ObservationVal = function(state, id, type, context, pe ...

Ignore linting errors in the Webpack React Fast Refresh plugin for faster performance

I have integrated the following plugin for Hot Module Replacement (HMR): https://www.npmjs.com/package/@pmmmwh/react-refresh-webpack-plugin. How do I prevent it from blocking the page display due to non-breaking errors, such as linting issues? Here is a ...

Tips for displaying a table with a button click

I am struggling to figure out how to embed a table inside a button in order to display the table when the button is clicked and hide it when clicked again. Below is the code I have been working with: function toggleTable(){ document.getElementById ...