2

I have a line that creates a simple box like so:

var box = $('<button>').addClass('box');

With using the css:

.box {
    border-radius: 0.7vw;
    width: 40vw;
    height: 50vw;
    margin: 30px;
    display: inline-block;
    background-color: #d87c2d;
}

All fine, I get those boxes, I can even click on them.

But what I really need is generating some usable elements.

For that, I usually like to keep components separate (hope I use the correct terminology), so I made a text file with the following content:

<div>
    <div class="tile" id="eventName"> Event name</div><br/>
    <div class="tile" id="eventDate">2017.01.01. </div>
    <div class="tile" id="eventTime">12.00</div><br/> 
    <div class="tile" id="description">Some boring example description about the meaningless </div>
</div>

My goal is to put this inside the $(-here-) instead of the simple <button> I have there.

To get that I tried

var box = $('/html/tileInside').addClass('box');

but didn't work, I believe JS thinks I want just the string /html/tileInside there which obviously doesn't mean anything.

So is there a way to add a string from a txt file inside the jQuery string selector?

agiro
  • 1,808
  • 1
  • 22
  • 49
  • there is no way jquery would know it is a string that somehow references some random file.... My guess is you want .load(), but I doubt that is what you really want.... – epascarello Oct 02 '17 at 12:07
  • 4
    Just FYI the HTML you're trying to create is invalid. You cannot place a `div` within a `button`. Having a `script` in there isn't a great idea either - especially ones which repeatedly include the same JS files. – Rory McCrossan Oct 02 '17 at 12:07
  • Thanks for the heads up. So after correcting the html, shall I just try to read the txt's content to a variable and put that inside? Or mess around with `innerHTML`? – agiro Oct 02 '17 at 12:10
  • 3
    As said, you cannot access a random file with javascript that simple. Consider using ajax `$(' – sofl Oct 02 '17 at 12:10
  • @sofl Thanks, it works. Do you want to convert that to an answer? – agiro Oct 02 '17 at 12:18

1 Answers1

2

Use ajax here.

$('<div></div>').load('/html/tileInside');

http://api.jquery.com/load/

http://api.jquery.com/jQuery.ajax/

sofl
  • 1,006
  • 8
  • 13