Skip CSS id as parameter in JavaScript function

I have a CSS id that shows a small red ball and a JAVASCRIPT function. I want to pass the CSS id as a parameter in a JavaScript function. I saw a lot of textbooks, but I can’t understand. Here are the codes:

CSS code

#projectile{
    position: absolute;
    background-color: #ff0000;
    left:176px;
    top: 486px;
    width:10px;
    height:10px;
    border-radius: 8px;
    z-index: 9;
}

JAVASCRIPT Code

function gofish(projectile_id){
var projectile = getElementbyId(projectile_id);
start_x = projectile.offset().left;
start_y = projectile.offset().top;

function init()
{ setTimeout("gofish('projectile')", 500); }
+4
source share
3 answers

Suppose you use jQuery and want the jQuery object to use a method offset(), since such a method does not exist for simple DOM nodes

function gofish(projectile_id){
    var projectile = $('#' + projectile_id);
    var start_x = projectile.offset().left;
    var start_y = projectile.offset().top;
}

function init() { 
    setTimeout(function() {
        gofish('projectile');
    }, 500); 
}
+2
source

You have some errors in your JavaScript.

  • getElementById must have a capital of "b" and must be called against the document.
  • , , , - element.offsetLeft element.offsetTop.
  • setTimeout init(), , adeneo.
  • init() - .

JavaScript:

function gofish(projectile_id) {
    var projectile = document.getElementById(projectile_id);
    start_x = projectile.offsetLeft;
    start_y = projectile.offsetTop;
}

function init() {
    setTimeout(function () {
        gofish('projectile');
    }, 500);
}

init();

, : http://jsfiddle.net/JuvDX/

+2

This may help you a bit.

    <!DOCTYPE html>
<html>
<head>

<script>
function myFunction(element)
{
alert(document.getElementById(element.id).value);
}
</script>
<style>
#para1
{
text-align:center;
color:red;
} 
</style>
</head>

<body>
<p id="para1" onclick="myFunction(this)" name="paragraph" >Hello World!</p>
</body>
</html>
0
source

Source: https://habr.com/ru/post/1533999/


All Articles