Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

159
Views
Use data-attribute in javascript to alter elements width

I am still new, so please forgive me if this question is too trivial or the issue has already been discussed. I didnt find anything specific, which led me to open a new question. That said, here is how it goes:

Im passing values from my database into data-attributes in order to use them in javascript to alter the width of certain elements (i.e. graphs). The element that should be altered according to the retrieved value is a p-Tag (together with others it sits inside a foreach):

<span class="fdpg-nut-vline"><p class="fdpg-nut-graph" id="graph" data-somedat="<?php echo "'" . $value['Nu_Val'] . "%'" ?>"></p></span>

The value of the data-attribute with the name "somedat" I want to use in js, like so:

var somevar = document.getElementById('graph').getAttribute("data-somedat");
document.getElementById("graph").style.width = somevar;

What I did?

  • I checked whether the format of the value is right. I therefore set a 'static' variable var somevartest = '20%'; and used it in the code above. It worked and the graph changed accordingly.
  • I checked if the value is passed into the data-attribute: (1) in the sourcode (its there!) and afterwards included an alert which shows me the value in the right format aswell (i.e. 'x%').

What is it that Im not getting? How can I solve my problem?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The proper way to pass data from PHP to JavaScript is using a JSON string.

PHP:

<?php
$arr = get_from_database_as_array(...);

// at end of page before your scripts:
echo "<script>";
echo "var data = " . json_encode($arr, true) . ";";
echo "</script>";

HTML:

<script>
  console.log(data); 
  document.getElementById("elem1").style.width = data["elem1"] + "px";
  document.getElementById("elem2").style.width = data["elem2"] + "px";
  // and so on.
</script>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!