walkman
walkman

Reputation: 109

how to display text in div dynamically

I have searched on the forum and saw posts about changing text dynamically upon click. But in my case I want to change the display dynamically when loading the page from beginning. I already have a function that figure out what I should display:

function phone()
{
//code here
return phone;
}

And my question is how to display the returned phone number in the div below to replace the 1.888.888.8888 part. Can anyone offer some insights? Thank you!

<div class="add-info">
<span class="rightfloat">Order online <span class="red">or call 1.888.888.8888</span></span>
</div>

Upvotes: 5

Views: 87167

Answers (6)

Alex K.
Alex K.

Reputation: 175796

You can,

<body onload="phone();">
    <div class="add-info">
        <span class="rightfloat">Order online <span class="red">or call
            <span id="phone"></span>
        </span>
    </div>
</body>

And set the value when the function runs;

function phone() {
    document.getElementById("phone").innerHTML = "1.888.888.8888";
}

Upvotes: 4

talemyn
talemyn

Reputation: 7950

I would change the HTML to add another <span> tag around the phone number and give that span tag an id attribute in order to access it easily (broke it up on separate lines to reduce scrolling):

<div class="add-info">
    <span class="rightfloat">
        Order online <span class="red">
            or call <span id="contact-number"></span>
        </span>
    </span>
</div>

Then after the page loads update the span with whatever value you want:

window.onload = function() {
    document.getElementById('contact-number').innerHTML = PHONE_NUMBER_VALUE;
}

In JQuery, it would be:

$(document).ready(function () {
    $('#contact-number').html(PHONE_NUMBER_VALUE);
});

Upvotes: 11

po228
po228

Reputation: 90

Try this

<script>
    function phone(number) {
        var redText = document.getElementByClassname("red")[0];
        redText.innerHTML = "or call " + number;
    }
</script>

To call it you can use clicks, loads or anything else. For example

<script>
    window.onload = phone('NEW NUMBER HERE');
</script>

Bear in mind that adding another window onload function later will displace this one, so you would either need to add to it, or use a double delegate function, but that's another story...

Upvotes: 0

Niro
Niro

Reputation: 776

Instead of returning 'phone', why don't you put an id on your span and just use document.getElementById('spanId').innerHTML = phone in your javascript?

Upvotes: 2

Gatekeeper
Gatekeeper

Reputation: 1616

I would separate the number into additional <span> tag with its own id and change content of it with js...

document.getElementById('id_of_span').innerText = 'new number';

Upvotes: 0

Matt Burland
Matt Burland

Reputation: 45135

Call you code from the window.onload event.

Upvotes: 0

Related Questions