Skip to content Skip to sidebar Skip to footer

Click On An Element Highlights Other Element

Is there any way to change the attributes of an element when clicking on another element? For example, consider this approach where I have a link like so: Clic

Solution 1:

This will work with multiple links:

change your css to:

.clickTarget.target {
    color: #4f8dd5;
}

give your links a common class ie link

$('a.link').on('click', function() {
   $('.target').removeClass('target');
   var id = $(this).attr('href');
   $(id).addClass('target');
   returnfalse;
});

http://jsfiddle.net/8S5mD/2/

Solution 2:

Add an attribute data-id (or other names) to your a link to specify the id of the associated span.

<ahref="#100"data-id="100">Click me!</a>

And here is javascript:

window.onload = function () {
    var alinks = document.getElementsByTagName('a');
    for (var i = 0; i < alinks.length; i++) {
        alinks[i].addEventListener('click', function () {
            var id = this.getAttribute('data-id');
            var span = document.getElementById(id);
            span.style.color = '#4f8dd5';
        });
    }
}

See example at jsFiddle

Solution 3:

Suppose something like this should work for you:

CSS:

.target{
       color:#4f8dd5;
    }   

HTML:

<ahref="#"data-target="#100">click me<a>

JS:

$(document).on("click", "a", function(e) {
   if($(this).data("target")) {
     e.preventDefault(); //just to avoid # appearing in address after click.
     $(".target").removeClass("target");
     $($(this).data("target")).addClass("target");
   }
})

This way ANY (even if it was added after code above is executed) link will run a function and if it has a data-target attribute, it will be used as a jquery selector to find an element which should be highlighted.

UPD:

Changed to reflect behavior of target (only one element should be highlighted at once) pointed by David Fregoli

Solution 4:

Try this one

    $("a").bind('click',function(e){
          if(!$("span.clickTarget").hasClass('changeTextColor')){
             $("span.clickTarget").addClass('changeTextColor');
           }
     });

css:

.changeTextColor {
         color: #4f8dd5;
    }

Post a Comment for "Click On An Element Highlights Other Element"