Thomas Varberg Thomas Varberg - 3 months ago 8
HTML Question

How to position text in javascript

I am new to JS and is looking for a way to set the position for a text for a html website.

my codes are.



function changeText(value) {
var div = document.getElementById("div");
var text = "";
var image = "";

if (value == 1) text += "this is picture one <br> <img class='custom_h_w' src='images/consumers_1.png'/>";
if (value == 2) text += "this is picture two <br> <img class='custom_h_w' src='images/consumers_2.png'/>";
if (value == 3) text += "this is picture tree <br> <img class='custom_h_w' src='images/consumers_3.png'/>";

div.innerHTML = text;
}

<a href="javascript: changeText(1);">
<img id="searchconsumers" src="images/search.png" width="40px" height="40px" alt="abc" />
</a>
<a href="javascript: changeText(2);">
<img id="exploreconsumers" src="images/explore.png" width="40px" height="40px" alt="abc" />
</a>
<a href="javascript: changeText(3);">
<img id="funconsumers" src="images/fun.png" width="40px" height="40px" alt="abc" />
</a>
<div id="div"></div>




Answer

I suggest to wrap your text by a span then create a new class using your text position rules, it'll be something like the following example.

Hope this helps.

function changeText(value) {
  var div = document.getElementById("div");
  var text = "";
  var image = "";

  if (value == 1) text += "<span class='custom_text_h_w'>this is picture one</span> <br> <img class='custom_h_w' src='http://www.xerys.com/images/xerys/1.png'/>";
  if (value == 2) text += "<span class='custom_text_h_w'>this is picture two</span> <br> <img class='custom_h_w' src='http://www.xerys.com/images/xerys/2.png'/>";
  if (value == 3) text += "<span class='custom_text_h_w'>this is picture tree</span> <br> <img class='custom_h_w' src='http://www.xerys.com/images/xerys/3.png'/>";

  div.innerHTML = text;
}
.custom_h_w{
  top: 120px;
  left: 100px;
  position: absolute;
}

.custom_text_h_w{
  top: 70px;
  right: 200px;
  position: absolute;
}
<a href="javascript: changeText(1);">
   <img id="searchconsumers" src="images/search.png" width="40px" height="40px" alt="abc" />
</a>
<a href="javascript: changeText(2);">
   <img id="exploreconsumers" src="images/explore.png" width="40px" height="40px" alt="abc" />
</a>
<a href="javascript: changeText(3);">
   <img id="funconsumers" src="images/fun.png" width="40px" height="40px" alt="abc" />
</a>
<div id="div"></div>