Marian
Marian

Reputation: 191

Convert jQuery to pure JavaScript

I'm having problems trying to convert this piece of code from jQuery into pure JavaScript.

I've wrote everything down in a JSFiddle as example.

The script is

$(".button").click(function () {
    $pageID = $(this).attr('name');
    var htmlString = $('#' + $pageID).html();
    $('#1').html(htmlString);
});

$(".button").click(function () {
    $(".button").css('background-position', '0px 0px');
    $(this).delay(50).css('background-position', '0px -40px');
});

$(document).ready(function () {
    $("[name='page1']").trigger('click');
});

For the first block I've used

function changeNavigation(id){
    document.getElementById('1').innerHTML=document.getElementById(id).innerHTML;
} 

And in each <div id="button"> added onclick="changeNavigation(id);" replacing id with page1 page2 etc for their respective buttons. Which seems to work fine. The problem is the second block of code.

I tried using

document.getElementById("button").style.background-position="0px -40px";

Changing the class to an id attribute, just to test it, but it doesn't work. What could be the problem? Is it that pure JS doesn't support background-position?

Also, as last thing, is it possible to use .innerHTML to write JS code? I've tried using both JS and jQuery to write Scripts and despite both writing the same exact thing, the written code didn't work with .innerHTML.

Upvotes: 1

Views: 1125

Answers (2)

Vinay
Vinay

Reputation: 6881

Try

style.backgroundPosition

instead of

style.background-position

Thanks to Anthony Grist.

You have used class not ID. So It would be something like

document.getElementsByClassName("button")[0].style.backgroundPosition="0px -40px"

Upvotes: 2

David Hedlund
David Hedlund

Reputation: 129792

The hyphen is not valid in property names in JavaScript. Therefore, the CSS property background-position is called backgroundPosition in JavaScript.

Upvotes: 0

Related Questions