Matthew
Matthew

Reputation: 113

How can I covert this inline javascript to jQuery function which is causing conflict?

I am using a jQuery language switcher and below is the working script.

<script type="text/javascript">
    window.lang = new jquery_lang_js();
    $(document).ready(function() {  
        window.lang.run();
    });
</script>

<a href="javascript:window.lang.change('jp');">Switch to Japanese</a>

However, the inline JavaScript is causing conflict with other jQuery scripts in the page.

I've tried to create a function like this below but obviously, this is not correct. By moving the .click function inside the document ready as suggested, it's working now.

<script type="text/javascript">
window.lang = new jquery_lang_js();
$(document).ready(function() {  
    window.lang.run();
});
$(".jp").click(function (e) {
    e.preventDefault();      
    var $this = $(this);        
    var id = $this.attr('href');
    window.lang.change('jp');
});

</script>

<a href="#" class="jp">Switch to Japanese</a>

Besides, I have other classes other than "jp" so this is not even the correct approach but I was trying to get rid of the inline javascript first; which I failed to do anyhow.

Can anyone please help?

/////////////////////Below works now ///////////////////

I guess now my question is, how can I rewrite it so that I do not repeat the code like this?

<script type="text/javascript">
window.lang = new jquery_lang_js();
$().ready(function () {
    window.lang.run();
 $(".jp").click(function (e) {
 e.preventDefault();      
        var $this = $(this);        
    var id = $this.attr('href');
    window.lang.change('jp');


 $(".en").click(function (e) {
 e.preventDefault();      
        var $this = $(this);        
    var id = $this.attr('href');
    window.lang.change('en');


});


});


</script>

<a href="#" class="jp">Switch to Japanese</a>
<a href="#" class="en">Switch to English</a>

. . . more classes

There is a better way than writing it like this, correct?

Upvotes: 1

Views: 329

Answers (1)

user1618143
user1618143

Reputation: 1748

You should move the .click() inside of the .ready(). Right now, that JavaScript is running before the anchor loads, so the $('.jp') isn't finding it.

Also, don't use $this as a variable; this isn't PHP, and you're not using it for anything important anyway.

Upvotes: 2

Related Questions