John Dangerous
John Dangerous

Reputation: 185

I need help consolidating my functions

I'm working on a project right now where I have a drop down and in the drop down there are many links. So what I am doing now is what I have below for each button. There are a lot of them.

$(".button1").click(function() {
    $(".contentContainer").load( "pages/functional_components_controlPanels.html" );
});

Will someone point out a more graceful way to do this to reduce my code down please? Any help would be much appreciated.

Upvotes: 1

Views: 45

Answers (1)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93561

Data-drive your code instead, using attributes on your button (or dropdown options, or links or whatever elements you like):

Example Html (with data- attributes for any extra values you need):

<input type="button" data-content="pages/functional_components_controlPanels.html"/>

Sample Code (makes use of data- attributes):

// Apply this only to inputs with data-content attributes (could be any filter you like)
$("input[data-content]").click(function() {

    // Extract values you need from attribute on the clicked item
    var content = $(this).data('content');

    // use the values to make decisions, specify parameters etc
    $(".contentContainer").load(content);
});

Plugins, like unobtrusive ajax, use data- attributes, so they do not have to be hard-wired to elements.

Attributes starting with the data- prefix are an allowed standard for browsers and are valid HTML (other attribute names are not always valid, so use the data- prefix).

Upvotes: 4

Related Questions