How do you properly write onclick events in JavaScript? - javascript

I'm trying to use an onclick event with an anchor tag that will change the innerHTML of another element on the page. I'm not sure what I'm doing wrong, so all the code I'm using is below. I hope you guys can point out my mistake and tell me what it was I misunderstood. The JavaScript file is included after the body, but you can see that on the JSfiddle here. So, when I click Settings, I want the BookmarkList div to show it's own HTML code, and the same for Home. The BookmarkList div will be the center of attention for this site. I'm just not sure what I'm doing wrong for this.
HTML:
<body id="bodyBG">
<div class="wrapper">
<div class="box header">
Header
</div>
<div class="box content">
<div class="box subcontent1">
<div class="sdfgsdfgsdfg"><input id="categoryName" placeholder="Category Name"></input></div>
<div class="sdfgsdfg"><input id="urlLink" placeholder="Site Address"></input></div>
<div class="sdfgsddfg"><input id="bookmarkName" placeholder="Bookmark Name"></input></div>
<div><button>Save</button></div>
<hr>
<input placeholder="Search Bookmarks"></input>
<button>Search</button>
</div>
<div class="box subcontent2">
Settings
<hr>
Home
Back
Forwards
</div>
<div id="bookmarkList" class="box subcontent3 bookmark-list">
</div>
</div>
<div class="box footer">Footer</div>
</div>
<script src="assets/js/bookmark-action-script.js"></script>
</body>
JavaScript:
var settingsNav = document.getElementById('settingsNav');
var homeNav = document.getElementById('homeNav');
var changeThis = document.getElementById("bookmarkList");
function myFunction(this) {
if (this === settingsNav) {
changeThis.innerHTML = "<h3>Bookmarks</h3><hr>";
}
else if (this === homeNav) {
changeThis.innerHTML = "<h3>Bookmarks</h3><hr><p>Store all your bookmarks here!</p><ul><li>An secure storage means for your privacy needs!</li><li>24/7 Availability</li></ul>";
}
else (this != settingsNav | homeNav) {
changeThis.innerHTML = "Nothing to see here!";
}
};
document.getElementById("settingsNav").addEventListener("click");
document.getElementById("homeNav").addEventListener("click");
The Solution:
I always add the solution that was appropriate for my problems, so future observers can see what issue I had and what the solution was. My issue was not adding the function to my eventlistener. You do not need to specify onclick events inside the HTML code if you specify event listeners with accompanying functions in your JavaScript code. But without the functions tied to the eventlisteners, nothing will happen. I understand that now.
var settingsNav = document.getElementById('settingsNav');
var homeNav = document.getElementById('homeNav');
var changeThis = document.getElementById("bookmarkList");
function myFunction(event) {
var el = this;
if (el === settingsNav) {
changeThis.innerHTML = "<h3>Bookmarks</h3><hr>";
} else if (el === homeNav) {
changeThis.innerHTML = "<h3>Bookmarks</h3><hr><p>Store all your bookmarks here!</p><ul><li>A secure storage means for your privacy needs!</li><li>24/7 Availability</li></ul>";
} else if (el != settingsNav || homeNav) {
changeThis.innerHTML = "Nothing to see here!";
}
};
document.getElementById("settingsNav").addEventListener("click", myFunction);
document.getElementById("homeNav").addEventListener("click", myFunction);

Remove attribute event handlers from HTML. Change function (this) to function (event). You did not add an event handler at.addEventListener()call, where you can passmyFunction` as a reference to to function to call when event is dispatched.
OR in JavaScript should be || instead of | at second else..if
Note, <input> element is self-closing, </input> is invalid HTML.
<body id="bodyBG">
<div class="wrapper">
<div class="box header">
Header
</div>
<div class="box content">
<div class="box subcontent1">
<div class="sdfgsdfgsdfg"><input id="categoryName" placeholder="Category Name"></div>
<div class="sdfgsdfg"><input id="urlLink" placeholder="Site Address"></div>
<div class="sdfgsddfg"><input id="bookmarkName" placeholder="Bookmark Name"></div>
<div><button>Save</button></div>
<hr>
<input placeholder="Search Bookmarks">
<button>Search</button>
</div>
<div class="box subcontent2">
Settings
<hr>
Home
Back
Forwards
</div>
<div id="bookmarkList" class="box subcontent3 bookmark-list">
</div>
</div>
<div class="box footer">Footer</div>
</div>
<script>
var settingsNav = document.getElementById('settingsNav');
var homeNav = document.getElementById('homeNav');
var changeThis = document.getElementById("bookmarkList");
function myFunction(event) {
var el = this;
if (el === settingsNav) {
changeThis.innerHTML = "<h3>Bookmarks</h3><hr>";
} else if (el === homeNav) {
changeThis.innerHTML = "<h3>Bookmarks</h3><hr><p>Store all your bookmarks here!</p><ul><li>An secure storage means for your privacy needs!</li><li>24/7 Availability</li></ul>";
} else if (el != settingsNav || homeNav) {
changeThis.innerHTML = "Nothing to see here!";
}
};
document.getElementById("settingsNav").addEventListener("click", myFunction);
document.getElementById("homeNav").addEventListener("click", myFunction);
</script>
</body>

Your code works fine in Chrome by fixing couple of syntax errors.
update else to else if
else if (clk != settingsNav | homeNav)
update this parameter to something else in myFunction
function myFunction(clk)
no need to add event since you called myFunction in onclick, so remove:
document.getElementById("settingsNav").addEventListener("click");
document.getElementById("homeNav").addEventListener("click");
Somehow it didn't work in jsfiddler.

Related

Showing a div only once per time when user on the site doesn't work?

I want to ask about javascript, how to show a div once in one visit?
I have the code that I have work below. But still not working.
JS Show Div Once Per Time
(function() {
var visited = sessionStorage.getItem('visited');
if (!visited) {
document.getElementById("popupMode").style.visibility = "visible";
sessionStorage.setItem('visited', true);
}
})();
What I want:
I have a popup div to give the user the option to choose the mode. When user have selected the popup will disappear. When I refresh the page I want the popup not appear again, it appears only once at the beginning of our visit to the web.
If you don't mind, I also have a switcher mode in the popup but it won't switch.
for the full code, you can see in My Codepen
POPUP MODE
<!-- Popup Mode -->
<div id="popupMode">
<div class="container-fluid p-0 h-100">
<div class="row h-100">
<div class="col-12 main-content">
<div id="modeChoice">
<div class="title">
<h2>Welcome</h2>
<p>
You can switch the button from light mode<br>to dark mode
</p>
</div>
<div class="choose-mode">
<div id="modeSwitcher">
<input type="checkbox" class="checkbox" id="chk" />
<label class="label" for="chk">
<i class="fas fa-moon"></i>
<div class="ball"></div>
</label>
</div>
</div>
<div id="buttonPopupMode">
UNDERSTAND
</div>
</div>
</div>
</div>
</div>
</div>
FULL JS
window.onload = function() {
(function() {
var visited = localStorage.getItem('visited');
if (!visited) {
document.getElementById("popupMode").style.visibility = "visible";
localStorage.setItem('visited', true);
}
})();
if (localStorage.darkMode == "true") {
document.body.classList.toggle('dark');
document.getElementById("chk").checked = true;
} else {
document.body.classList.toggle('light');
}
};
document.getElementById("chk").addEventListener('change', () => {
document.body.classList.toggle('dark');
document.body.classList.toggle('light');
localStorage.darkMode = (localStorage.darkMode == "true") ? "false" : "true";
});
$("#popupMode").delay(3000).fadeIn(500);
$("#buttonPopupMode .button-primary").on('click', function() {
$('#popupMode').hide();
})
Move this line $("#popupMode").delay(3000).fadeIn(500); inside if (!visited) {...}.
Updated code will be like below.
window.onload = function() {
(function() {
var visited = localStorage.getItem('visited');
if (!visited) {
document.getElementById("popupMode").style.visibility = "visible";
localStorage.setItem('visited', true);
// Add below line.
$("#popupMode").delay(3000).fadeIn(500);
}
})();
if (localStorage.darkMode == "true") {
document.body.classList.toggle('dark');
document.getElementById("chk").checked = true;
} else {
document.body.classList.toggle('light');
}
};
document.getElementById("chk").addEventListener('change', () => {
document.body.classList.toggle('dark');
document.body.classList.toggle('light');
localStorage.darkMode = (localStorage.darkMode == "true") ? "false" : "true";
});
// remove below line.
// $("#popupMode").delay(3000).fadeIn(500);
$("#buttonPopupMode .button-primary").on('click', function() {
$('#popupMode').hide();
})
P.S.
localStorage vs sessionStorage
localStorage and sessionStorage accomplish the exact same thing and have the same API, but with sessionStorage - the data is persisted only until the window or tab is closed, while with localStorage - the data is persisted until the user manually clears the browser cache or until your web app clears the data. I would suggest to use localStorage but its up to you and your requirement you can choose preferable.

Problems with javascript event handler

I'm hoping this doesn't get marked as "duplicate", because I have reviewed several threads and followed the advice I found. I know I'm missing something simple, and need other eyes on this. I'm a newbie, so please bear with me. I am testing a simple button element that I have a click event handler on, but it is not working. It works inline with "onclick", but I am trying to avoid that. The simple html:
<div>
<button id='handler'>Event</button>
</div>
<div id='stringText'>
<h4>Some Description</h4>
<p>
Some more information
</p>
</div>
And the javascript:
<script>
document.getElementById("handler").addEventListener("click", display, true);
function display() {
if (document.getElementById("stringText").style.display === "block") {
document.getElementById("stringText").style.display = "none";
} else {
document.getElementById("stringText").style.display = "block";
}
};
</script>
I have the css that initially sets the "stringText" display as "none". I appreciate any assistance.
Probably your problem is related to the execution of that script while the document is being loaded.
Add this condition stringText.style.display === "" to show/hide the elements correctly.
An alternative is using the event DOMContentLoaded
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
document.getElementById("handler").addEventListener("click", display, true);
function display() {
var stringText = document.getElementById("stringText");
if (stringText.style.display === "block" || stringText.style.display === "") {
stringText.style.display = "none";
} else {
stringText.style.display = "block";
}
};
});
<div>
<button id='handler'>Event</button>
</div>
<div id='stringText'>
<h4>Some Description</h4>
<p>
Some more information
</p>
</div>
Please allow some delay to load the pages using window.onload events
<div>
<button id='handler'>Event</button>
</div>
<div id='stringText'>
<h4>Some Description</h4>
<p>
Some more information
</p>
</div>
<script>
window.onload = function(){
document.getElementById("handler").addEventListener("click", display, true);
};
function display() {
if (document.getElementById("stringText").style.display === "block") {
document.getElementById("stringText").style.display = "none";
} else {
document.getElementById("stringText").style.display = "block";
}
};
</script>
If you make sure and set the initial display property to block it works fine. As an alternative, you could also try using jQuery, as I have in the snippet.
//with jquery
$(document).ready(function() {
$('#handler').on('click', function() {
$('#stringText').toggleClass('hide');
})
})
.hide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<button id='handler'>Event</button>
</div>
<div id='stringText'>
<h4>Some Description</h4>
<p>
Some more information
</p>
</div>

object HTMLImageElement popping in jQuery funtion

I have 2 images displayed on a page. I want a message to appear when I click 1 image and it to disappear when I click the alternate one, then vice versa.
The jQuery code I created below seems to be working fine, but I am continuously getting an [object HTMLImageElement] message on the alternate image every time I click the one that is displaying the text.
$(document).ready(function(){
$("#gimp").click(function(){
var gimp = "Gimp message.";
var i = $("#qInkscape").text(inkscape);
if (i == true) {
$("#qInkscape").hide();
$("#qGimp").text(gimp);
} else {
$("#qGimp").text(gimp);
}
});
$("#inkscape").click(function(){
var inkscape = "Inkscape message";
var g = $("#qGimp").text(gimp);
if (g == true) {
$("#qGimp").hide();
$("#qInkscape").text(inkscape);
} else {
$("#qInkscape").text(inkscape);
}
});
});
And the html
<div class="mf-container">
<div class="mf-content">
<div class="row">
<div class="mf-third mf-center">
<img src="img/qualifications/gimp_g.png" class="mf-pic-unique mf-pic-
shadow mf-margin-top" id="gimp" alt="about gimp">
<p id="qGimp" class="mf-off-black-text"> </p>
</div>
<div class="mf-third mf-margin-top">
<p class="mf-center mf-off-black-text">Click on an image to learn more
about each technology</p>
</div>
<div class="mf-third mf-center">
<img src="img/qualifications/inkscape_G.png" class="mf-pic-unique mf-
pic-shadow mf-margin-top" id="inkscape" alt="about inkscape">
<p id="qInkscape" class="mf-off-black-text"> </p>
</div>
</div>
</div>
</div>

LinkButton.Text coming undefined in js

I want to configure a hyperlink to close/open its related div in asp.net. Basically, when a user clicks the sign X, the panel should be closed and the sign + should be appeared. When + is clicked, the panel should be showed again. I could not manage this and I believe my main problem is "document.getElementById('<%= lb_closePanel.ClientID %>').value" is coming as undefined. Here is the code until now. I appreciate for your helps!
<!DOCTYPE html>
....
<div class="appheader">
<h1 class="appheaderContent">Search for Client</h1>
<div id="checkBox"></div>
<div id="closePanel"><h2 id="lblClosePanel">Close Panel</h2>
<div id="xButton">
<asp:LinkButton onclientclick="CloseOpenPanel('Search')" runat="server" Text="X" style="text-decoration:none; color:white" ID="lb_closePanel"></asp:LinkButton>
</div>
</div>
</div>
<div class="app" id="Search">
...
<div>
...
</html>
<script type="text/javascript">
function CloseOpenPanel(obj) {
alert(document.getElementById('<%= lb_closePanel.ClientID %>').value); //here it comes undefined!!!!
if (document.getElementById('<%= lb_closePanel.ClientID %>').value == 'X') {
document.getElementById(obj).Visible = false;
lb_closePanel.Text = '+';
}
else {
document.getElementById(obj).Visible = true;
lb_closePanel.Text = 'X';
}
}
</script>
Your code is OK, just instead of the property value use innerHTML
alert(document.getElementById('<%= lb_closePanel.ClientID %>').innerHTML);
Instead of using .value, try using .innerHTML instead to get the text inside of your link button (rendered as an a tag)

Attaching event handler to DOM elements

I am working on a tic tac toe game, which is almost complete. The only thing I am left wondering about is if it is possible to add an event handler for onclick from my .js file instead of directly calling it from an HTML attribute. Here is the bit of HTML that uses the onclick:
<div id="left">
<div id="board">
<div id="one" onclick="playerMove(this)">
</div>
<div id="two" onclick="playerMove(this)">
</div>
<div id="three" onclick="playerMove(this)">
</div>
<div id="four" onclick="playerMove(this)">
</div>
<div id="five" onclick="playerMove(this)">
</div>
<div id="six" onclick="playerMove(this)">
</div>
<div id="seven" onclick="playerMove(this)">
</div>
<div id="eight" onclick="playerMove(this)">
</div>
<div id="nine" onclick="playerMove(this)">
</div>
</div>
</div>
Any thoughts on the matter would be greatly appreciated.
If you use jQuery something like this should work:
$(document).ready(function() {
$('#board div').click(playerMove);
});
In plain javascript (no cross platform libraries), event handlers can be added via javascript code with addEventListener (modern browsers) or attachEvent (older versions of IE).
Here's a simple function that adds an event handler in a cross browser fashion:
// add event cross browser
function addEvent(elem, event, fn) {
if (elem.addEventListener) {
elem.addEventListener(event, fn, false);
} else {
elem.attachEvent("on" + event, function() {
// set the this pointer same as addEventListener when fn is called
return(fn.call(elem, window.event));
});
}
}
Example usage (called after the page DOM has loaded):
addEvent(document.getElementById("one"), 'click', playerMove);
Or, to install event handlers for all the board divs, you could do this:
var divs = document.getElementById("board").children;
for (var i = 0, len = divs.length; i < len; i++) {
// element nodes only
if (divs[i].nodeType === 1) {
addEvent(divs[i], 'click', playerMove);
}
}
You should really consider using jQuery for this. If you were using jQuery, this would have been as simple as:
$('#board > div').click(playerMove);
In case you want to stick with vanilla JS, you can do:
var items = document.getElementById('board').children;
for(x in items) {
items[x].onclick = function() {
playerMove(items[x]);
};
}
Use this:
document.getElementById('element_id').onclick = function(){ playerMove(this); };
For each Div, change 'element_id' with 'one', 'two', ...
Try:
document.getElementById('one').onclick();
For binding the event handler in js file:
var board = document.getElementById('board'),
divs = board.getElementsByTagName('div'),
i, len = divs.length;
for (i = 0; i < len; i++) {
divs[i].onclick = function() {
playerMove(this);
};
}
Your answer is in following 5 lines. Try it :) If someone copies/converts my code in new post or my post to j-query, That is welcome with no problem.
var yourDivID = document.getElementById('your_Div_ID');
yourDivID.addEventListener('click', function (){ playerMove(this); }, false);
function playerMove(divElement)
{
alert(divElement.id);
}
I have tried to put complete demo Here on jsfiddle.net, You can click any div out of nine to check its event if link does not work, then you can check the following code (working for me WIN7 and FireFox)
<html>
<head>
<title> Add Events Dynamically </title>
<script type="text/javascript">
function add_DivClick_Events() {
var nodes = document.getElementById('board').childNodes;
for (var i = 0; i < nodes.length; i++) {
if (i % 2 == 1) {
nodes[i].addEventListener('click', function () {
playerMove(this);
}, false);
}
}
}
function playerMove(divElement)
{
alert(divElement.id);
}
</script>
<style type="text/css">
#board div
{
width:20px;
height:20px;
border:2px solid;
}
</style>
</head>
<body onload='add_DivClick_Events()'>
<div id="left">
<div id="board">
<div id="one">
</div>
<div id="two">
</div>
<div id="three">
</div>
<div id="four">
</div>
<div id="five">
</div>
<div id="six">
</div>
<div id="seven">
</div>
<div id="eight">
</div>
<div id="nine">
</div>
</div>
</div>
</body>
</html>

Categories

Resources