0

I've written a forEach loop which goes through an array of divs (by ID), selects child elements with a certain class and removes another class from them. I'm having a few issues turning the variable back into a selector and joining it to the other ones. As a result, my forEach loop doesn't work.

http://jsfiddle.net/NWmB5/7/ (Try clicking one of the links, the third item should turn black again if the code works)

var toDoCategories; 

$(document).ready(function() {

toDoCategories = [$("#testDiv"),$("#anotherDiv"),$("thirdDiv")]; 
setTimelinePosition($('#thirdDiv'));

$('#targetFirstDiv').click(function() {
setTimelinePosition($('#anotherDiv'));

});
$('#targetSecondDiv').click(function() {
setTimelinePosition($('#testDiv'));

});

});


/* Show current position on timeline */
function setTimelinePosition($position) {


var $theTimelineTrigger = $('span.timelineTrigger');

toDoCategories.forEach(function(currentCategory) {


var $deselectTimelinePositionElement = $(currentCategory, $theTimelineTrigger);

$($deselectTimelinePositionElement).removeClass('currentPosition');
});
3
  • 1
    You're missing a # in the thirdDiv selector, and this entire approach is horrible. Commented Jan 10, 2014 at 13:33
  • jsfiddle.net/NWmB5/8 Commented Jan 10, 2014 at 13:35
  • Thanks @adeneo. Whilst this code is only for an HTML prototype (and isn't going near production without a proper Developer rewriting most of it) I'd like to make it less "horrible". I think a sensible thing would be to apply a common class to all of the divs with the IDs which I later place in the array and use it to generate the array. I'd appreciate any tips you might have to make the developers less offended by this. Commented Jan 10, 2014 at 13:36

1 Answer 1

1

It should be as simple as

$(document).ready(function () {

    var $toDoCategories = $("#testDiv, #anotherDiv, #thirdDiv"); //NOTE HERE

    setTimelinePosition('#thirdDiv');

    $('#targetFirstDiv').click(function () {
        setTimelinePosition('#anotherDiv');
    });
    $('#targetSecondDiv').click(function () {
        setTimelinePosition('#testDiv');
    });

    /* Show current position on timeline */
    function setTimelinePosition(position) {
        $toDoCategories.find('.currentPosition').removeClass('currentPosition')
        $(position).find('.timelineTrigger').addClass('currentPosition');
    }
});

Demo: Fiddle


Another approach: Fiddle

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Arun. I'll have a go with the second approach you recommended.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.