Scroll
Using Chat GPT to rewrite javascript code without jQuery
Prompt for ChatGPT to Rewrite jQuery to JavaScript
If you want to rewrite jQuery code into pure JavaScript using ChatGPT, navigate to chat.openai.com and enter the following clear, concise prompt:
Please rewrite the following jQuery code into vanilla JavaScript, maintaining the same functionality. Ensure compatibility with modern JavaScript standards (ES6+). Also, include usage of Drupal.behaviors if applicable. [Paste your jQuery code here]
Replace the placeholder [Paste your jQuery code here] with the actual jQuery code you want to convert.
Here is an example of jQuery to javascript code:
(function ($, Drupal) {
Drupal.behaviors.myBehavior = {
attach: function (context, settings) {
// Only run once per element per page load
$('.my-class', context).once('myBehavior').each(function () {
$(this).click(function () {
alert('Element clicked: ' + $(this).text());
});
});
// Example of adding a class dynamically
$('.toggle-button', context).once('toggleBehavior').click(function () {
$('.toggle-target').toggleClass('active');
});
}
};
})(jQuery, Drupal);
Re-writen javascript code without jQuery:
(function (Drupal) {
Drupal.behaviors.myBehavior = {
attach: function (context, settings) {
context.querySelectorAll('.my-class').forEach(function(element) {
if (!element.dataset.myBehaviorAttached) {
element.dataset.myBehaviorAttached = true;
element.addEventListener('click', function () {
alert('Element clicked: ' + element.textContent);
});
}
});
context.querySelectorAll('.toggle-button').forEach(function(button) {
if (!button.dataset.toggleBehaviorAttached) {
button.dataset.toggleBehaviorAttached = true;
button.addEventListener('click', function () {
document.querySelectorAll('.toggle-target').forEach(function(target) {
target.classList.toggle('active');
});
});
}
});
}
};
})(Drupal);