Matthew
Matthew

Reputation: 113

How to convert javascript inline code to jQuery?

I have this working jQuery + inline javascript which causes a conflict with existing jQuery.

<script>
var jq=jQuery.noConflict(); 
function goto(id, t){   
    jq(".contentbox-wrapper").animate({"left": -(jq(id).position().left)}, 600);
    jq('#slide a').removeClass('active');
    jq(t).addClass('active');   
}
</script>
<a class="active" href="#" onClick="goto('#kr', this); return false">
<a class="active" href="#" onClick="goto('#en', this); return false">

(I've tried to resolve the conflict as you can see but I believe the conflict arises from the inline javascript.)

How can I convert this inline javascript? Thanks.

Upvotes: 1

Views: 323

Answers (3)

Matthew
Matthew

Reputation: 113

$('.active').on('click', function() {
var $this = $(this);        
var id = $this.attr('href');
$(".contentbox-wrapper").animate({"left": -($(id).position().left)}, 600);
$('#slide a').removeClass('active');
$this.addClass('active');
return false;
 });

huangism answered it for me. https://stackoverflow.com/users/1058134/huangism

Upvotes: 0

Roko C. Buljan
Roko C. Buljan

Reputation: 206171

Inline JS (embed into HTML) is hardly maintainable, I'd suggest:

HTML:

<div id="parent"> <!-- or any other parent el. -->
    <a href="#">Anchor</a>
</div>

jQuery:

(function($){ // remap $ to jQuery

  $(function(){ // DOM ready

    $('#parent').on('click', 'a', function( ev ){
       ev.preventDefault();
       var krPos = $('#kr').position().left;
       $(".contentbox-wrapper").animate({"left": -krPos }, 600);
       $('#slide a').removeClass('active');
       $(this).addClass('active'); 
    });

  });

})(jQuery);

Upvotes: 0

techfoobar
techfoobar

Reputation: 66663

You can bind it like:

<script>
//var jq=jQuery.noConflict();   
function goto1(id, t){   
    ...
    return false; // return false to prevent the link's default action
}

// means once your DOM is ready, and a.active is available to be bound
$(document).ready(function() { 

    // bind all clicks on a.active to the function 'goto1'
    $('a.active').click(goto1);
});
</script>

Variable names like goto can be potential causes of confusion later on. Changed it above to goto1.

Upvotes: 1

Related Questions