Why Can't I Call a Function Named Clear from an Onclick Attribute

Why can't I call a function named clear from an onclick attribute?

Intrinsic event attributes (like onclick) are horrible. Internally they implement with:

Use of the with statement is not recommended, as it may be the source of confusing bugs and compatibility issues.

Consequently, you are actually calling document.clear() instead of your global clear().

The quick fix for this is to rename the function to something else or explicitly call window.clear().

The better solution is to bind your event handlers with addEventListener instead of intrinsic event attributes.

Sample Image

HTML onclick event doesn't work with parameter

Your problem is using open - although not a reserved word - in the onclick which performs a document.open (I would have guessed window.open) and that will wipe the page in any case

Rename the function but I strongly recommend you remove the inline event handler and use an eventListener

I added the IDs of the divs to show as data attribute to the buttons you click

document.addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.classList.contains("project-button")) {
const more_info = document.getElementById(tgt.dataset.id);
more_info.classList.toggle("project-closed");
}
})
.project-box {
padding: 2vh;
margin-bottom: 3vh;
box-shadow: 0px 5px 7px rgb(136, 136, 136);
}

.project-button {
width: 20vw;
height: 3vh;
background-color: #d6d6d6;
border: none;
}

.project-button:hover {
background-color: #B50000;
color: white;
}

.project-button:focus,
.project-button:active,
.project-button:visited {
border: none;
border-radius: 0;
}

.project-closed {
display: none;
}

* {
font-family: Arial, Helvetica, sans-serif;
font-size: 2vh;
}
<div class="project-box" id="project_1">
<h3>Project 1</h3>
<p>description</p>
<div class="project-closed" id="project_info_1">
<p>Informations</p>
</div>
<button type="button" class="project-button" data-id="project_info_1">More details</button>
</div>

<div class="project-box" id="project_2">
<h3>Project 2</h3>
<p>description</p>
<div class="project-closed" id="project_info_2">
<p>Informations</p>
</div>
<button type="button" class="project-button" data-id="project_info_2">More details</button>
</div>

Why is my onclick event not executing?

I think its,becuse submit is a built in function for the form. Try calling your function something else, or add id to your button and attach onclick using jquery on method.

$('#buttonid').on('click', function() { // do stuff });



Related Topics



Leave a reply



Submit