Skip to content

Instantly share code, notes, and snippets.

@ruturajpatki
Last active September 5, 2023 05:50
Show Gist options
  • Select an option

  • Save ruturajpatki/fbd1442f2080dd1fd1bc920ef024ae18 to your computer and use it in GitHub Desktop.

Select an option

Save ruturajpatki/fbd1442f2080dd1fd1bc920ef024ae18 to your computer and use it in GitHub Desktop.
To attach a jQuery event with a wildcard CSS selector, you can use the `on` method along with a custom filter function that matches elements based on a pattern. If you want the event handler to work for dynamically added elements, you should use event delegation. Event delegation allows you to attach an event handler to a parent element that alr…
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="button-container">
<!-- Existing buttons -->
<button id="item1">Item 1</button>
<button id="item2">Item 2</button>
<button id="item3">Item 3</button>
</div>
<button id="add-button">Add Button</button>
<script>
$(document).ready(function() {
// Event delegation for dynamically added buttons
$('#button-container').on('click', '[id^="item"]', function() {
// Your event handler code here
alert('Clicked on an item with an ID starting with "item"');
});
// Function to add a new button dynamically
$('#add-button').on('click', function() {
var newButtonId = 'item' + ($('[id^="item"]').length + 1);
$('#button-container').append('<button id="' + newButtonId + '">Item ' + ($('[id^="item"]').length + 1) + '</button>');
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment