jQuery toggleClass example
Toggle class name on click in jQuery
by tawowohzyk
HTML
<div id="message">
<button>Change color</button>
</div>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#message {
background: #fff;
border-radius: 4px;
padding: 20px;
font-size: 25px;
text-align: center;
transition: all 0.2s;
margin: 0 auto;
width: 300px;
}
JavaScript
function sendEvent(eventName) {
const apiHost = "http://localhost/NOT_EXIST_API/event_collect";
if (navigator.sendBeacon) {
// 設定送出的資料
// https://developer.mozilla.org/en-US/docs/Web/API/FormData
const data = new FormData();
data.set("event", eventName);
// 送出beacon
var status = navigator.sendBeacon(apiHost, data);
console.log(`event(beacon): ${status}`);
} else {
// 不支援
// 設定jquery ajax
const settings = {
data: {
method: 'POST',
event: eventName,
}
};
jQuery.ajax(apiHost, settings)
.done(function() {
console.log("event(AJAX): ok");
})
.fail(function() {
console.log("event(AJAX): fail");
});
}
}
// find elements
var button = $("button");
// handle click and add class
button.on("click", () => {
sendEvent("wryyyyy");
});