js trigger

box1
box2

box3
box4
<style>
#box1 {width: 100px; height: 100px; background-color: red;}
#box2 {width: 100px; height: 100px; background-color: cyan;}
#box3 {width: 100px; height: 100px; background-color: green;}
#box4 {width: 100px; height: 100px; background-color: magenta;}
</style>
<body>
<div id="box1">box1</div>
<div id="box2">box2</div>
<div id="message1"></div>

<hr>

<div id="box3">box3</div>
<div id="box4">box4</div>
<div id="message2"></div>
<script>
;(function() {
	document.addEventListener('DOMContentLoaded', function() {
		clickBox1();
		clickBox2();
	});
	var box1 = document.getElementById('box1');
	var box2 = document.getElementById('box2');
	var message1 = document.getElementById('message1');

	function clickBox1() {
		box1.addEventListener('click', function() {
			message1.textContent = '';
			message1.textContent = 'box1がクリックされました。';
		});
	}

	function clickBox2() {
		box2.addEventListener('click', function() {
			triggerEvent(box1, 'click');
		});
	}

	function triggerEvent(elm, e) {
		var evt = document.createEvent("HTMLEvents");
		evt.initEvent(e, true, true ); // event type, bubbling, cancelable
		return elm.dispatchEvent(evt);
	}
})();
</script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
;(function() {
	$(function() {
		clickBox3();
		clickBox4();
	});

	var box3 = $('#box3');
	var box4 = $('#box4');
	var message2 = $('#message2');

	function clickBox3() {
		box3.on('click', function() {
			message2.text('').text('box3がクリックされました。');
		});
	}

	function clickBox4() {
		box4.on('click', function() {
			$('#box3').trigger('click');
		});
	}

})();
</script>


PAGE TOP