Diego Rafael Souza
Diego Rafael Souza

Reputation: 5313

How can I create a user control having it's own css and javascript

I'm implementing something like suggested on this question, having a dynamically generated user control nested in another one.

The issue I'm facing is that some controls have some javascript functions or css classes that are not being loaded.

For example, I have a control that resume to this ListBox:

<div class="form-group listbox-align" style="width:100%;">
    <asp:ListBox ID="ListBox_Options" runat="server" CssClass="multiselect-group listbox-element" AutoPostBack="false"></asp:ListBox>
</div>

And the css classes exclusive to this control (listbox-align and listbox-element) looks like this:

.listBox-align {
    text-align: left;
}

.listBox-align .input-group-btn {
    display: none;
}

When loading page I have this javascript code to this component:

$(document).ready(function () {
    var listBox = '#<%=ListBox_Options.ClientID %>';

    Sys.Application.add_load(function () {
        aplicarComponenteOctopusSearchable(listBox, '100%');
    });
});

function aplicarComponenteOctopusSearchable(seletor, btnWidth) {
    try {
        $(seletor).multiselect({
            includeSelectAllOption: false,
            allSelectedText: 'All',
            selectAllText: 'All',
            nSelectedText: 'Selected',
            nonSelectedText: 'Select...',
            buttonWidth: btnWidth,
            maxHeight: 400,
            enableFiltering: true,
            filterPlaceholder: 'Filter...',
            enableCaseInsensitiveFiltering: true
        });
    } catch (e) {
        alert(e.message);
    }
}

Now I'm unable to use this component properly 'cause I couldn't figure out how to load this css and javascript just once and just on the pages that use this user control (it'll be added after some event).

Can anyone help me with this?

Upvotes: 1

Views: 238

Answers (1)

Brad
Brad

Reputation: 3591

I have this function that I wrote in Javascript that you call like this:

loadjscssfile(RelativeFilePathToFile, "css") 

I used it to add or update existing CSS classes in an easter egg on key press events, but you dont need all that. But it works to add new CSS or add a new CSS class that will override an existin global one.

It has been a while but it should work with Javascript files as well, just look at the function on what to pass to add them.

// this function is to add an additional javascript or CSS file on demand to a page
function loadjscssfile(filename, filetype) {
    if (filetype == "js") { //if filename is a external JavaScript file
        var fileref = document.createElement('script')
        fileref.setAttribute("type", "text/javascript")
        fileref.setAttribute("src", filename)
    }
    else if (filetype == "css") { //if filename is an external CSS file
        var fileref = document.createElement("link")
        fileref.setAttribute("rel", "stylesheet")
        fileref.setAttribute("type", "text/css")
        fileref.setAttribute("href", filename)
    }
    if (typeof fileref != "undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref)

    this.IsSwap = true;

} // end function to load js/css files

// updated to add this, I have used this one to remove a file once it is loaded. It worked for CSS files (I had shortcut keys to add/remove a .css file as an easter egg to change the layout), not sure if this works with javascript:

function removejscssfile(filename, filetype) {
    var targetelement = (filetype == "js") ? "script" : (filetype == "css") ? "link" : "none" //determine element type to create nodelist from
    var targetattr = (filetype == "js") ? "src" : (filetype == "css") ? "href" : "none" //determine corresponding attribute to test for
    var allsuspects = document.getElementsByTagName(targetelement)
    for (var i = allsuspects.length; i >= 0; i--) { //search backwards within nodelist for matching elements to remove
        if (allsuspects[i] && allsuspects[i].getAttribute(targetattr) != null && allsuspects[i].getAttribute(targetattr).indexOf(filename) != -1)
            allsuspects[i].parentNode.removeChild(allsuspects[i]) //remove element by calling parentNode.removeChild()
    }

    this.IsSwap = false;

}

call it like this:

 removejscssfile(RelativePathYouPassedToDynmaicallyAddtheFileHere, "css")

Upvotes: 2

Related Questions