I'm having trouble properly calling the function twice and obtaining the desired output. Can anyone provide assistance?

I am facing an issue with a function that is supposed to draw a line based on its parameters. The problem arises when I make multiple calls to this function. The first function call yields the expected output, however, subsequent calls do not display the line from the first function call. Instead, only the line from the latest function call is shown. Any suggestions on how to resolve this?

function draw_vertical_line(width, height, linecolor, xpos, ypos) {
  $('.line').css({
    'width': width,
    'height': height,
    'background-color': linecolor,
    'left': xpos,
    'bottom': ypos,
    'position': 'absolute'
  });
}

draw_vertical_line(10, 500, '#357d35', 50, 100); //This line does not show
draw_vertical_line(10, 300, '#357d35', 300, 200); //This line shows
<div class="line"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Answer №1

I trust that my assistance has been beneficial

        function draw_vertical_line(id, width, height, linecolor, xpos, ypos) {
            $('#'+id).css({
                'width': width,
                'height': height,
                'background-color': linecolor,
                'left': xpos,
                'bottom': ypos,
                'position': 'absolute'
            });
        }

        draw_vertical_line('line1', 10, 500, '#357d35', 50, 100);  
        draw_vertical_line('line2', 10, 300, '#357d35', 300, 200);
    <div id="line1"></div>
    <div id="line2"></div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Enhanced solution:

function draw_vertical_line(lines) {
    for (let i = 0; i < lines.length; i++) {
        $('#wrap').append('<div class="line' + i + '"></div>');
        $('.line' + i).css({
            'width': lines[i][0],
            'height': lines[i][1],
            'background-color': lines[i][2],
            'left': lines[i][3],
            'bottom': lines[i][4],
            'position': 'absolute'
        });
    }
}

// List of lines
draw_vertical_line([
    [10, 500, '#357d35', 50, 100],
    [10, 300, '#357d35', 300, 200],
    [10, 200, '#cccccc', 100, 400],
    [10, 100, '#888888', 200, 500],
    [10, 300, '#222222', 600, 200]
]);
    <div id="wrap"></div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Answer №2

An important issue arises when using $(".line") because it will consistently move the same line, resulting in only the last movement being visible.

If you want to add new lines for each call, you can achieve this by:

var div = $("<div>");
div.css({...});
$("body").append(div);

(or replace "body" with your preferred container for the lines if it's not specified)

Alternatively, to streamline the process and leverage jQuery chaining, you can do:

$("<div>").css({...}).appendTo("body"); 

Here is an updated code snippet:

function draw_vertical_line(width, height, linecolor, xpos, ypos) {
  $("<div>").css({
    'width': width,
    'height': height,
    'background-color': linecolor,
    'left': xpos,
    'bottom': ypos,
    'position': 'absolute'
  }).appendTo('body');
}

draw_vertical_line(10, 500, '#357d35', 50, 100); 
draw_vertical_line(10, 300, '#357d35', 300, 120);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

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

Updating dynamic parameter in a NextJS 13 application router: A complete guide

In my route user/[userId]/forms, I have a layout.tsx that includes a Select/Dropdown menu. The dropdown menu has options with values representing different form IDs. When the user selects an item from the dropdown, I want to navigate to user/[userId]/form ...

incorporate information into D3 with React

Greetings! I am currently working on a line graph that should display dynamic data. In cases where no data is provided, it will simply show a straight line. My current challenge lies in passing the props to the line graph component. var data `[ { &quo ...

Unlocking the Power of Observable Objects with Knockout.js

Recently delving into knockoutjs, I came across the Microsoft tutorial showcasing how to integrate knockoutjs with MVC Web API. The tutorial can be found at: https://www.asp.net/web-api/overview/data/using-web-api-with-entity-framework/part-8. In a particu ...

Successfully transferring canvas image to server. Saving empty picture file

I have a piece of code that creates an image from an equation editor when the save button is clicked and displays it on a canvas. However, after displaying it, I am having trouble saving it as the saved image appears blank. Can someone please help me ident ...

Using the same geometric shapes repeatedly leads to occasional texture errors in THREE.JS

As I embark on my journey to create my first card game using THREE.js for Firefox and Chrome, I have encountered a perplexing issue with disappearing textures. The purpose of this post is to gain insights into why this issue occurs and how I can resolve i ...

How do I utilize Protractor to target a specific div element with a distinctive class and verify its visibility on the page?

Below is the view.html for a unique class: <div class="appExperience small-tile"> </div> This is the code snippet that I attempted to use: var displayedTile = element(by.css('.appExperience small-tile')); expect(displayedTile.i ...

Access JSON information from the identical document

Trying to showcase Google charts using data from a MySQL database has been successful with separate PHP and JS files. However, the aim is to streamline the process by handling data in a single file. Here's a snippet of the current setup: $table = ...

Experiencing a 401 error when making an AJAX call to BigCommerce's API

I am attempting to reach the Minimum Purchase Quantity on quick search results by utilizing jQuery/AJAX to call an API. However, we are encountering a challenge as the API is not responding and instead displaying the following error message: NetworkErro ...

Combining HTML, CSS, JAVASCRIPT, and PHP for a seamless web development experience

As a beginner in web development, I have some knowledge of javascript, html, css and am currently delving into php. However, I am struggling to find comprehensive resources that show how to integrate all these languages together. I would greatly appreciat ...

"Experience the power of using Selenium with Node.js in an asynchronous function

I'm currently developing a simple program that retrieves the titles of all the links when conducting a search on Google using Selenium Take a look at the code below: const {Builder,By, Key, until} = require('selenium-webdriver'); driver = ...

What is the most efficient method in React for displaying an array as a table and wrapping every set of five elements with a <tr> tag?

Currently, I am working on rendering a table in React from an array of objects. My approach involves mapping the array to create table elements as shown below: var objects = response.data; var arrayOfTableElements = [] ...

What is the best way to display changing data in a React component?

Having some trouble with printing data based on the length of an array. Here is my attempted solution, but unfortunately, it's not working as expected. I believe the issue lies in the cb function within the forEach loop. Below is the code snippet: fun ...

Addressing an error of "call stack full" in nextjs

I am currently working on a project in nextjs where I need my billboard to continuously scroll to show different information. The Nextjs debugger keeps showing me an error message that says 'call stack full'. How can I resolve this issue? con ...

Angular Persistent States in Angular version 2 and beyond

Currently, I am in the process of transitioning an Angular 1.5.X application to Angular 4. Within my app, I incorporate Angular Ui-Router Sticky State from https://github.com/ui-router/sticky-states to prevent loss of content within my view when navigating ...

Expand or collapse Angular Material Accordion depending on selected Radio button choice

Is it possible to use a mat-accordion with radio buttons where each panel expands only when its corresponding radio button is selected? I have the radio buttons functioning correctly, but the panels are expanding and collapsing with every click rather than ...

Exporting Textures with Custom Offsets to GLTF from Three.js Scene

UPDATE: I was initially puzzled about exporting to obj and mtl formats, but then I stumbled upon the GLTFExporter.js in three.js which allowed me to successfully extract both the geometry and texture from my project. However, a new challenge arose with t ...

AWS Amplify-hosted Nuxt applications are resilient to errors during the build process

My website is built using Nuxt js and hosted on AWS Amplify. I've encountered a major issue where the website still gets generated successfully even when there's a failure in the nuxt generate command (like a JavaScript error in my code). Below i ...

Fetch information that was transmitted through an ajax post submission

How can I retrieve JSON formatted data sent using an ajax post request if the keys and number of objects are unknown when using $_POST["name"];? I am currently working on a website that functions as a simple online store where customers can choose items m ...

Persisting jQuery UI position in database and showing it on the screen

i am currently working on a project using jquery ui for resizing and drag and drop features. i need to figure out how to save these changes in a database. here is the progress i have made so far: http://plnkr.co/edit/rAwEs6eUS2JPmFMxqQ?p=preview i am look ...

What is the best way to display a variable (string/int) from a PHP file onto an HTML file?

I've searched online multiple times for a solution, but most of the results I found only show how to echo HTML code from a PHP file by changing the file extension to .php. However, my goal is to echo a variable from a PHP file and display it in an HTM ...