0

i have a Eventlistener, that can to change css position. Now i want to set up second function, which can remove previous Eventlistener . this is html code:

<style> 
div.container {
    width: 300px;
    border: 1px solid;
}

div.box {
    width: 150px;
    border: 3px solid coral;
    float: left;
    padding: 10px;
}
</style>
</head>
<body>

<div class="container">
<div class="box" id="box1">This is BOX1.</div>
<div class="box" id="box2">This is BOX2.</div>
<div style="clear:both;"></div>
</div>

<p>Two 150 pixels boxes inside a 300 pixels container. It should fit nicely, but because of the borders and padding, the two boxes take up more space than 150 pixels each. This "problem" can be solved by setting the boxSizing property to "border-box".</p>




<button onclick="myFunction()">Try it</button>

da this is Javascript:

<script>
function myFunction() {

    document.getElementById("box1").style.boxSizing = "border-box";
    document.getElementById("box2").style.boxSizing = "border-box";
}


</script>
3
  • When do you want to remove the event listener? Commented Feb 26, 2016 at 12:29
  • After user will execute myFunction(). Also after Box position will change on "border-box" Commented Feb 26, 2016 at 12:30
  • duplicate of stackoverflow.com/questions/4402287/… Commented Feb 26, 2016 at 12:33

1 Answer 1

1

The cleanest way to remove listeners is to bind it with addEventListener, and then remove it with removeEventListener. Such as:

var el = document.getElementById("myButton");

function listener(e) {
  // do things on event
}

// adding the event
el.addEventListener("click", listener, true);

// removing the event
el.removeEventListener("click", listener, true);

Notice that both addEventListener and removeEventListener are REFERENCING the listener function. You need that reference to later remove the event listener, thats how the removeEventListener method works.

Full answer has been covered before: JavaScript: remove event listener

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.