简体   繁体   中英

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 .

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"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM