JSFiddle - React, Tailwind, and code Playground
by dshilkret
HTML
<div ng-app="myApp" ng-controller="myCtrl">
<button id="showButton" ng-click="showItems()" autofocus>Show Items</button>
<ul ng-show="itemsVisible">
<li ng-repeat="item in items">{{ item.name }}</li>
</ul>
</div>
CSS
button {
margin: 10px;
padding: 5px 10px;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
JavaScript
//AngularJS w/vanilla js for autofocus
angular.module('myApp', []).controller('myCtrl', ['$scope', '$document', function($scope, $document) {
$scope.items = [
{ name: "Item 1", id: 1 },
{ name: "Item 2", id: 2 },
{ name: "Item 3", id: 3 }
];
$scope.itemsVisible = false;
$scope.showItems = function() {
$scope.itemsVisible = true;
if(!$scope.$$phase) $scope.$apply();
};
// Set focus on the button when the controller initializes
var button = document.getElementById('showButton');
if (button) {
button.focus();
}
// Add event listener for 'keypress' event on the button
button.addEventListener('keypress', function(event) {
if (event.keyCode === 13) { // Enter key
$scope.showItems();
}
});
// Clean up the event listener when the scope is destroyed
$scope.$on('$destroy', function() {
if (button) {
button.removeEventListener('keypress', $scope.showItems);
}
});
}]);
/*
//AngularJS without vanilla js for autofocus as seen above.
angular.module('myApp', []).controller('myCtrl', ['$scope', '$timeout', function($scope, $timeout) {
// Using $timeout to wait for the DOM to render before setting focus
$timeout(function() {
var button = document.getElementById('showButton');
if(button) {
button.focus();
}
});
$scope.items = [
{ name: "Item 1", id: 1 },
{ name: "Item 2", id: 2 },
{ name: "Item 3", id: 3 }
];
$scope.itemsVisible = false;
$scope.showItems = function() {
$scope.itemsVisible = true;
};
// Rest of your controller code...
}]);
*/