Search code examples
javascriptseadragon

basic scripting question... dynamically modify div content?


I'm wondering what might be the simplest approach to dynamically changing the contents of a "caption" div to reflect the info corresponding to a specific thumbnail/link in an image gallery.

To be more specific, if you visit this link-- which shows off the awesome Seadragon zoom script btw-- I would like to have a small caption under the image that changes (text) content when a user clicks the different links above; perhaps pulling text from an alt or title attribute and placing in an empty div?

In my case, I'll be using thumbnails instead of text links, so upon clicking these images the user will both initiate the "switchTo" Seadragon event and fill the empty div with corresponding content.

thanks for any guidance here.


Solution

  • If you have the id of the div, the simplest way would be to use innerHTML:

    document.getElementById(id).innerHTML = "text";
    

    This is fine for simpler cases, like replacing all of the text in a div. If you want to do something more complicated, like having other html elements inside the div, this method is not the best choice.

    If you want to add an html element to the div tag, then you should avoid innerHTML. If you have, say, a variable img that is an img tag, then use this to add it to the div:

    document.getElementById(id).appendChild(img);
    

    If you want to do anything more complicated than this, you should probably consider using a nice framework like jQuery--it might be too much for something like this, but if you plan to do anything else, then a framework would be worth using.

    If you want to do this with jQuery, it can be done using some of the following functions:

    var div = $("#id");// jQuery uses CSS selectors to get elements.
    div.append("New content");// Puts the new content at the end.
    div.empty();// Gets rid of everything inside the div.
    div.append(element);// You can also append elements.
    
    // For example, you can create and append an image to the div:
    var img = $("<img>");
    img.attr("src", "images/something.png");
    div.append(img);