unique ID for the component in CQ5

By Erum Karim via flickr

If you have to deal with javascript, divs and component you could end in the problem that unique Id in a component page is not so unique. If you for example have an html/javascript like

<div id="myDiv"></div>
<script type="text/javascript">document.getElementById("myDiv").innertHTML="Hello World!";</script>

will work fine if you include your component only once in your page. But if you include it more than that you’ll get some unpredictable behaviors, but for sure it wont work.

In order to solve the problem, you can for example use the currentNode in the jsp using his getIdentifier() method.

<div id="<%=currentNode.getIdentifier()%>"></div>
<script type="text/javascript">document.getElementById("<%=currentNode.getIdentifier()%>").innertHTML="Hello World!";</script>

Done, done!

Advertisements

3 thoughts on “unique ID for the component in CQ5

  1. I used some javascript to solve this problem for myself using jquery.

    //assign unique (incremental id) to each top-level component container
    $(‘.mycomponent’).each(function(index){
    if (!$(this).attr(‘id’).length) {
    $(this).attr(‘id’,’mycomponent-‘+index);
    }
    });

    Now I can iterate through instances of my component and more easily target objects within.

  2. The problem I would like some help in solving. How do I build components that have javascript and css dependencies that I only need to load once regardless of how many instances of the component are loaded. I currently have a small lazyLoad.js script with a callback method; which minimizes some of this. The lazyLoad.js script will load multiple times but on the first run it loads resources and sets a flag in a global scoped js var so it also checks for that flag on each load, thus on subsequent component inclusions; it skips additional loads. Although, I noticed just yesterday this wasn’t working for me in IE9.

  3. @ecropolis

    Regarding js, you can define a function and before loading (in the component) the js file you can do a test like: if(typeOf(myFunction)==’undefined’){//not loaded}.

    Regarding CSS instead I don’t know.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s