Simos Sigma
Simos Sigma

Reputation: 978

Refresh X div elements at once using an html button. How to make my code shorter?

I have three divs and one button. In to my jQuery script, everytime I click on button, those three divs elements refreshed at once.

HTML Code

<input id="refresh" type="button" value="Refresh"/>
<div id="R1">Value 1</div>
<div id="R2">Value 2</div>
<div id="R3">Value 3</div>

JQUERY CODE

var $JQ_ = jQuery.noConflict();

$JQ_(document).ready(function () {

    $JQ_("#refresh").click(function () {
        $JQ_("#R1").load("index.php#R1").fadeOut(1000).fadeIn(1000);
    });
    $JQ_("#refresh").click(function () {
        $JQ_("#R2").load("index.php #R2").fadeOut(1000).fadeIn(1000);
    });
    $JQ_("#refresh").click(function () {
        $JQ_("#R3").load("index.php #R3").fadeOut(1000).fadeIn(1000);
    });
});

JSFIDDLE Example here.

What I want to do is to make my code shorter and not to have to write the same thing for all my divs. In to an other script I am using something like this

 $JQ_("[id^='opener_']").click(function () {
     $JQ_("#dialog_" + this.id.split('_')[1]).dialog("open");
 });

but this is an other case. Any idea how can I make my code work like this?

Upvotes: 1

Views: 866

Answers (2)

Matthew Rapati
Matthew Rapati

Reputation: 5686

<input id="refresh" type="button" value="Refresh"/>
<div id="R1" data-url="index.php #R1" class="thing">Value 1</div>
<div id="R2" data-url="index.php #R2" class="thing">Value 2</div>
<div id="R3" data-url="index.php #R3" class="thing">Value 3</div>

Add a class to each "thing". In the click event, loop through each "thing", get the url to load the data from the data-url attribute, and do the stuff:

$JQ_("#refresh").click(function() {
    $JQ_('div.thing').each(function() {
        var url = $JQ_(this).data('url');

        $JQ_(this).load(url).fadeOut(1000).fadeIn(1000);
    });
});

Upvotes: 4

m3h2014
m3h2014

Reputation: 154

Put the divs you want to refresh into one class and use the class identifier for your jQuery code. This will allow you to run jQuery code on multiple divs without having to copy-paste the same code for each div.

Upvotes: 2

Related Questions