Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call javascript function on page load in mvc3

I have a javascript function

function relativeTime(time) {

var period = new Date(time);
var delta = new Date() - period;

if (delta <= 10000) {   // Less than 10 seconds ago
    return 'Just now';
}

var units = null;

var conversions = {
    millisecond: 1,     // ms -> ms
    second: 1000,   // ms -> sec
    minute: 60,         // sec -> min
    hour: 60,       // min -> hour
    day: 24,        // hour -> day
    month: 30,      // day -> month (roughly)
    year: 12            // month -> year
};

for (var key in conversions) {
    if (delta < conversions[key]) {
        break;
    }
    else {
        units = key;
        delta = delta / conversions[key];
    }
}

// Pluralize if necessary:

delta = Math.floor(delta);
if (delta !== 1) { units += 's'; }
return [delta, units, "ago"].join(' ');

}

that give relative time difference like facebook comment.

How can i call this function in my view. I am using mvc3. i am getting time from database like,

        <span>
            @item.wallTimeStamp
        </span>

instead of that i want to call javascript function,

i have a tag

<span>
    //call javascript function that will display time difference in this tag
   </span>

how can i do that?

like image 925
Bhargav Avatar asked Sep 05 '11 10:09

Bhargav


2 Answers

First, give the span id(or something else for identification)

<span id="relativeTime">
</span>

Then, using javascript, first calculate that relative time value using your function. Then, using jQuery.text(), set that value inside span

<script>

$(document).ready(function() {
  var wallTimeStamp = '@item.wallTimeStamp';

  var relativeTimeValue = relativeTime(wallTimeStamp);

  $('#relativeTime').text(relativeTimeValue);
});

</scipt>

Code modification may be needed for multiple spans of that kind

like image 198
archil Avatar answered Sep 19 '22 09:09

archil


$(document).ready(function() {
 //called when the document is ready
});
like image 42
Bozho Avatar answered Sep 19 '22 09:09

Bozho