Question

I have a group of 31 divs each with a numerical class. I am trying to make it so all the divs with a class of todays date or earlier animate when clicking a submit button.

<div class="image 1">SAMPLE TEXT</div>
<div class="image 2">SAMPLE TEXT</div>
<div class="image 3">SAMPLE TEXT</div>
<div class="image 4">SAMPLE TEXT</div>
<form>
   <input class="previous" type="submit" value="View Previous" />
</form>

And this bit of jQuery, but it far from works and I can not for the life of me figure out why.

$("form").submit(function() 
    {
    var number = $('div.image').attr("class").match(/\d+/),
        d = new Date(),
        day = d.getDate();

    if (number <= day){
        $('div.image').animate({"height":"0px", "width":"150px", "bottom":"75px"}, 500);
    }
    else {
    }
});

I currently have it so each individual div animates when you hover over them, but i want to also be able to animate a group of them when clicking the submit button. Thank you!

Was it helpful?

Solution

The first : You have to return false from function form submit (don't reload page). Then

d = new Date(),
day = d.getDate();

$(".image").each(function(i,e){
    var number = $(e).attr("class").match(/\d+/);
    if (number <= day)
        $(e).addClass('active'); 
});

and

$('div.active').animate({"height":"0px", "width":"150px", "bottom":"75px"}, 500);

OTHER TIPS

Because the form already submit before the animate begin to run You should add return false after the animate

like that

if (number <= day){

    $('div.image').animate({"height":"0px", "width":"150px", "bottom":"75px"}, 500);

    return false;
}

else {

}

Why not use a custom attribute on the div? Try something like this.

HTML:

<div class="image" number="1">SAMPLE TEXT</div>
<div class="image" number="2">SAMPLE TEXT</div>
<div class="image" number="3">SAMPLE TEXT</div>
<div class="image" number="4">SAMPLE TEXT</div>
<form>
   <input class="previous" type="submit" value="View Previous" />
</form>

JavaScript:

$('div.image').each(function()
{
    var number = $(this).attr('number'),
        d = new Date(),
        day = d.getDate();

    if (number <= day){
        $(this).animate({"height":"0px", "width":"150px", "bottom":"75px"}, 500);
    }
});

To test the above, add it into your "OnSubmit" or "OnHover" event handler...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top