Rick D
Rick D

Reputation: 55

Click event to call a js file, then load contents into div

I would like to be able to click on the Orange text to be able to call the orange.js file, then load the .js file into the myTableResult div. I would like the name of the .js file to be inside the onclick event. Can somebody help me with that?

<a onclick="getScript('Orange.js');"/>Orange</a>

<div id="myTableResult">


</div> 
<script type="text/javascript" src="/myapp/htmlCode"></script>

Upvotes: -4

Views: 143

Answers (3)

RobyOneG
RobyOneG

Reputation: 1

maybe you need to especify a little bit more your question, but here is an example of html and js injection.

First i prefer to use button instend of a just because the side effects of a tag element here is the code:

<button type="button" onclick="getScript('orange')">Orange</button>

<div id="myTableResult"></div>

<script type="text/javascript">
    const getScript = (fileName) => {
        const scriptElement = document.createElement("script");
        scriptElement.type = "text/javascript";
        scriptElement.src = `./js/${fileName}.js`;
        document.getElementsByTagName("body")[0].appendChild(scriptElement);
    }
</script>

Then on my "orange.js" file i do something like this:

const dummyHeaders = [
    'ID',
    'Name',
    'Status'
];

const dummyData = [
    {id: 0, name: 'orange', status: true},
    {id: 1, name: 'apple', status: true},
    {id: 2, name: 'strawberry', status: true},
];

const init = () => {
    // get div reference
    const element = document.getElementById('myTableResult');

    // create table and added to dom
    const table = document.createElement('table');
    element.appendChild(table);

    // create table headers and added to dom
    const thead = document.createElement('thead');
    table.appendChild(thead);

    const trHeads = document.createElement('tr');
    thead.appendChild(trHeads);

    for(let dataHeads of dummyHeaders) {

        // create new th element for each header setted
        const th = document.createElement('th');
        th.textContent = dataHeads;
        trHeads.appendChild(th);
    }

    
    // table body
    const tbody = document.createElement('tbody');
    table.appendChild(tbody);

    for(let data of dummyData) {

        // create new row for each object in array and added to the dom
        const trBody = document.createElement('tr');
        tbody.appendChild(trBody);

        // get each property of the element iterated
        const dataTd = Object.getOwnPropertyNames(data);
        for(let tdInfo of dataTd) {
            // create a new td element for each property on the object
            const td = document.createElement('td');
            td.textContent = data[tdInfo];
            trBody.appendChild(td);
        }
        
    }


}

init();

Upvotes: -2

hamed danesh
hamed danesh

Reputation: 502

if you are using jquery, you can use:

$.getScript( "ajax/test.js", ()=>{
// after load
}
});

to get the script and execute whatever command you want in the after load section (call functions, .etc).

if you are using vanilla javascript, then you need to first add your script to document body and then call any function you want like this:

    function getScript(srcFile){
        const script = document.createElement('script');
        script.src = srcFile;
        document.head.appendChild(script);
    }

And to pass result to your element you need to do

jquery:

$('#myTableResult').html(your_html_goes_here)

vanilla js:

document.getElementById("myTableResult").innerHTML="your_html_goes_here"

Upvotes: 0

jQueeny
jQueeny

Reputation: 8291

You want to append HTML to the DOM so given a file named Orange.html containing the following HTML:

Orange.html

<table>
    <tr>
        <th>Name</th>
        <th>Sweetness</th>
        <th>Size</th>
    </tr>
    <tr>
        <td>Valencia</td>
        <td>9</td>
        <td>8</td>
    </tr>
    <tr>
        <td>Jaffa</td>
        <td>10</td>
        <td>7</td>
    </tr>
</table>

index.html

<a href="#" 
   class="load-table-link" 
   data-file="./Orange.html" 
   data-destination="myTableResult">Orange
</a>
<div id="myTableResult"></div>

The following code will allow you to append the table to the DOM using fetch:

// Select all load-table-link a tags
const loadLinks = document.querySelectorAll('.load-table-link');
// Loop through them and add click events
if(loadLinks.length){
    for(const link of loadLinks){
        link.addEventListener('click', (e)=>{
            e.preventDefault();
            // Get filename from data-file attribute
            const file = e.target.dataset.file;
            // Get target div from data-destination attribute
            const destination = e.target.dataset.destination;
            addFileToDestination(file, destination);
        })
    }
}
const addFileToDestination = (file, destination) =>{
    fetch(file).then(response => {
        return response.text();
    }).then(data => {
        const section = document.createElement('section');
        section.innerHTML = data;
        document.querySelector(`#${destination}`).appendChild(section)
    });
}

I have made the code extensible so for each <a href="#" class="load-table-link"> you just need to add the name of the file containing your html tables in the data-file attribute and the target div id in the data-destination attribute.

Upvotes: 0

Related Questions