2
votes

Hello Fellow Developers, I am new to PhoneGap, have not coded in a number of years, and have an issue with the addEventListener below.

The alert which i am sampling in the addEventListener in the javascript below is being displayed always, even if the user does not click the button, the event is called and the alert is displayed. I would like to ensure the alert is only displayed when the button is actually clicked.

Any help that you can provide would be awesome.

Cheers Dre

var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
onDeviceReady: function() {
alert("PhoneGap is working in index.js onDeviceReady");
var buttonTwo = document.getElementById("btnPageTwo");

// the below event listener is fired always, even without the user clicking or performing any action the alert is displayed
buttonTwo.addEventListener('click', alert("Button Clicked"), false);
app.receivedEvent('deviceready');
},

// Update DOM on a Received Event
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');

listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');

console.log('Received Event: ' + id);
}
};

app.initialize();
<html>
<head>
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<link rel="stylesheet" type="text/css" href="css/index.css">
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<title>Multipage Document Lesson 09</title>
</head>
<body>
<p>First Page</p>
<button id="btnPageTwo">Go to Page 2</button>
</body>
</html>
1

1 Answers

1
votes

You are using alert directly in add event. use function instead

buttonTwo.addEventListener('click',function(){ alert("Button Clicked");}, false);