简体   繁体   中英

How to activate an element by triggering a click event using Javascript?

I have an div element and set a default color. When it is active the color changes. So, when clicking using a mouse the color will change to red. I'm also triggering a click event when the DOM is ready. But, when I trigger the click event the behavior is not the same. The element does not change color and it disappears. What is the best way to achieve it?

Here is the jsfiddle: https://jsfiddle.net/uvcwxLjr/ .

var ele = document.querySelector('.clickMe');
ele.addEventListener('click', function() {
  alert('You\'ve clicked me');
});
ele.click();

I know it can be done by creating another class that has background red and add that when mouse down and remove when mouse up. Is there a better way?

 $(function () { $(".clickMe").click(function () { $(this).css('background-color', 'green'); alert('change green'); }); }); 
  .clickMe { width: 100px; height: 100px; background-color: red; } 
  <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script> <div class="clickMe"> </div> 

'alert' function will block ui thread in browser( more info ), in other words, alert blocked the div to be rendered with red color. Alternatively, you can use console.log , like this :

var ele = document.querySelector('.clickMe');
ele.addEventListener('click', function() {
 console.log('You\'ve clicked me');
});
ele.click();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM