Javascript onclick event not firing on first click - javascript

The code below is a link which when clicked will open and close an initially hidden div. It works fine other than having to click the link twice in the first instance to open it. It's not a major problem but if it can be made so that the div opens on the first click that would be great.
toggleDiv.js
function toggleDiv(elem, eventType, handler) {
if (elem.addEventListener) {
elem.addEventListener(eventType, handler, false);
} else {
elem.attachEvent('on' + eventType, handler);
}
}
toggleDiv(window, 'load', function() {
var link = document.getElementById('myMagicLink'),
div = document.getElementById('foo');
toggleDiv(link, 'click', function() {
if (!link) return true;
if (div.style.display == "none") {
div.style.display = "block"
} else {
div.style.display = "none"
}
return true;
});
});
index.html
<body>
<a id="myMagicLink" href="http://www.google.com/">My Magic Link</a>
<div id="foo">Opens a div</div>
<br>
End of page
<br>
<script language="JavaScript" type="text/javascript" src="toggleDiv.js"></script>
</body>

I had the same problem for toggling the display value of an ASIDE tag. Switching from "none" to "inline" and back again would not work on the first click. Display was set to "none" in my CSS file.
In my script I changed "none" to "" (which seems to mean "default" as far as I understand). The following code works fine for me now.
var x = document.getElementsByTagName("aside")[0];
if (x.style.display == "")
{
x.style.display = "inline";
}
else
{
x.style.display = "";
}
I understood this when I saw the CSS/actual values in Firefox developer tools: "aside" is shown with CSS attributes, but an "element" is first shown with no attribute. On first click, "element" was assigned a "display" attribute set to "none".

Not sure what the trouble you are having this... this works flawlessly for me in Chrome.
I did change the url of your link to reflect back to the same document, but the div foo is hiding and reappearing as it should.
Couple of style notes: Rather than setting display = "block" it is better to say display = "" so it can return to its default value.
In addition, I also included a preventDefault function. Your use of return true would work for DOM0 style event handling, but it did not work with the attachEvent/addEventHandler code. This properly keeps the link from being followed.
<html>
<head>
<title>Test</title>
<script>
function toggleDiv(elem, eventType, handler) {
if (elem.addEventListener) {
elem.addEventListener(eventType, handler, false);
} else {
elem.attachEvent('on' + eventType, handler);
}
}
toggleDiv(window, 'load', function() {
var link = document.getElementById('myMagicLink'),
div = document.getElementById('foo');
toggleDiv(link, 'click', function(e) {
if (!link) return cancelDefaultAction(e);
if (div.style.display == "none") {
div.style.display = "block"
} else {
div.style.display = "none"
}
return cancelDefaultAction(e);
});
});
function cancelDefaultAction(e) {
var evt = e ? e:window.event;
if (evt.preventDefault) evt.preventDefault();
evt.returnValue = false;
return false;
}
</script>
<body>
<a id="myMagicLink" href="#">My Magic Link</a>
<div id="foo">Opens a div</div>
<br>
End of page
<br>
</body>
</html>

Sorry it seems a bit complicated for something pretty simple, unless you have a specific design in mind; but this should work equally well:
The Fiddle
<html>
<head>
<script language="JavaScript" type="text/javascript">
var toggled = false;
function toggleDiv()
{
if(toggled)
{
document.getElementById('foo').style.display = '';
toggled = false;
}
else
{
document.getElementById('foo').style.display = 'none';
toggled = true;
}
}
</script>
</head>
<body>
<a id="myMagicLink" href="http://www.google.com/" onClick='toggleDiv()'>My Magic Link</a>
<div id="foo">Opens a div</div>
<br>
End of page
<br>
</body>
</html>
​

Related

How to fix: Script Causing Page Refresh (return false; not working)

I have two javascript functions. The one shows and hides div's by their ID. This has been working fine until now. I have since added some code I found online that prevents iOS from opening links in a new window (when in fullscreen mode). Since adding this new code everytime I click on a div to show/hide it, the functions fires but then the page refreshes. Any help?
I have tried to put return false in every conceivable place.
I changed my onclick to 'return function();'.
I changed it to 'function();return false'.
I placed return false inside both functions.
(function(document,navigator,standalone) {
//Code by Irae Carvalho http://about.me/irae
// prevents links from apps from oppening in mobile safari
// this javascript must be the first script in your <head>
if ((standalone in navigator) && navigator[standalone]) {
var curnode, location=document.location, stop=/^(a|html)$/i;
document.addEventListener('click', function(e) {
curnode=e.target;
while (!(stop).test(curnode.nodeName)) {
curnode=curnode.parentNode;
}
if('href' in curnode ) {
e.preventDefault();
location.href = curnode.href;
}
return false;
},false);
}
})(document,window.navigator,'standalone');
function showHidden(id) {
var div = document.getElementById(id);
if (div.style.display == 'none') {
div.style.display = '';
}else{
div.style.display = 'none';
}
return false;
}
<!-- The code below is in my php file -->
<a onclick="showHidden('divID')">
Clicking on the link fires the showHidden function correctly but then it also refreshes the page. I need the event listener to prevent iOS from opening links in a new window when in fullscreen mode but I also don't want the click listener to fire when I use the showHidden function, or at the least not refresh the page.
The reason it is changing pages is because you are not preventing the default action of a link click, which is in this case loading a different page. You can do this by invoking e.preventDefault() when the link is clicked.
Here is an example:
(function(document,navigator,standalone) {
//Code by Irae Carvalho http://about.me/irae
// prevents links from apps from oppening in mobile safari
// this javascript must be the first script in your <head>
if ((standalone in navigator) && navigator[standalone]) {
var curnode, location=document.location, stop=/^(a|html)$/i;
document.addEventListener('click', function(e) {
curnode=e.target;
while (!(stop).test(curnode.nodeName)) {
curnode=curnode.parentNode;
}
if('href' in curnode ) {
e.preventDefault();
location.href = curnode.href;
}
return false;
},false);
}
})(document,window.navigator,'standalone');
function showHidden(id) {
var div = document.getElementById(id);
if (div.style.display == 'none') {
div.style.display = '';
}else{
div.style.display = 'none';
}
return false;
}
var links = document.querySelectorAll('a');
links.forEach(function (el) {
el.addEventListener('click', function (e) {
e.preventDefault();
var divID = this.getAttribute('hide-id');
showHidden(divID)
})
})
<a hide-id="div1">Click here</a>
<div id="div1">
This is content
</div>
<br />
<br />
<a hide-id="div2">Click here</a>
<div id="div2">
This is content
</div>
The best solution I found to this was to add a check in the eventlistener to check if the href tag was not empty:
if(curnode.href != '' )
And only after that firing the redirect:
location.href = curnode.href;

Toggling visibility of multiple texts is not working

I am trying to toggle between a couple of texts, where the only one that shows is the one that was "turn on" most recently. For example, the default would look something like this:
Click A
Click B
If you click 'Click B', the text for that will toggle to something else, let's say "You've clicked B".
Click A
You've Clicked B
If you click 'Click A' right afterwards, then the previous text will go back to its default, ie "You've Clicked B" will revert back to 'Click B' and then 'Click A' will be turn on.
Right now, neither of them are toggling, they are just both on.
Here is what I have:
JavaScript
toggle_visibility("t1");
toggle_visibility("t2");
function toggle_visibility(id) {
function toggle(id){
var text = document.getElementById(id);
if(text.style.display == 'none'){
text.style.display = 'block';
}
else{
text.style.display = 'none';
}
}
toggle(id);
}
HTML
<div id="t1" <a href="Click A" onclick="toggle_visibility('t1');">
<h1>You've Clicked A</h1></div>
<div id="t2" <a href="Click B" onclick="toggle_visibility('t2');">
<h1>You've Clicked B</h1></div>
It's better if you assign an id to the <h1> tag like this and I have added some attributes:
<div> <a href="#" onclick="toggle_visibility('t1');">
<h1 id="t1" data-original="Click A" data-after="You've clicked A" data-toggled="0">Click A</h1></div>
<div> <a href="#" onclick="toggle_visibility('t2');">
<h1 id="t2" data-original="Click B" data-after="You've clicked B" data-toggled="0">Click B</h1></div>
For the JS, you can use this:
<script>
var isFirst = true;
function toggle_visibility(id) {
if(!isActivated(id)) {
toggle(id);
if(isFirst != true) {
if(id == "t1") {
toggle("t2");
} else if(id == "t2") {
toggle("t1");
}
}
}
isFirst = false;
}
function toggle(id) {
var text = document.getElementById(id);
if(text.getAttribute("data-toggled") == "1") {
text.setAttribute("data-toggled", "0");
text.innerHTML = text.getAttribute("data-original");
}
else {
text.innerHTML = text.getAttribute("data-after");
text.setAttribute("data-toggled", "1");
}
}
function isActivated(id) {
var element = document.getElementById(id);
if(element.getAttribute('data-toggled') == "1") {
return true;
} else {
return false;
}
}
</script>
Check your HTML first.
<div id="t1">**** <a href="Click A" onclick="toggle_visibility('t1');">
<h1>You've Clicked A</h1></div>
<div id="t2">**** <a href="Click B" onclick="toggle_visibility('t2');">
<h1>You've Clicked B</h1></div>
There should be a closing ">" near the place I marked ****. Again, you have not closed your anchor tag with an "</a>"
I can't be sure that I interpreted your HTML correctly (there are several errors in it), but other than that, I believe this solves the problem:
var visibleText;
function toggle_visibility(id) {
var text = document.getElementById(id).lastElementChild;
if (text.style.display === 'none') {
if (visibleText) visibleText.style.display = 'none';
visibleText = text;
text.style.display = 'block';
} else {
text.style.display = 'none';
}
}
This code keeps track of any currently toggled-on 'text' in a variable declared outside the scope of the toggle_visibility function. This allows you to easily toggle off any currently visible text and switch on the desired text.
And here's a JSFiddle.

JavaScript: How can I change the visibility of an element when clicked?

I'm trying to make a code that allows me to make click on any part of the screen and when I click the screen should display the message "click!"
By far I got the next code
html:
<html>
<head>
<title>Sense events anywhere</title>
<script type="text/javascript" src="anywhere.js"></script>
<link type="text/css" rel="stylesheet" href="anywhere.css" />
</head>
<body id="body" onload="init();">
<div id="message"> Click! </div>
</body></html>
JavaScript:
var e;
function init(){
e = document.getElementById("message");
document.getElementById("message").style.visibility = "hidden";
e.onmousedown = displayIt(e);
e.onmouseup = hideIt;
}
function displayIt(e) {
e.style.visibility = "visible";
}
function hideIt() {
e.style.visibility = "hidden";
}
CSS:
body {
}
div#message{
}
By far I only tried to turn the message visible and "invisible" when clicked but it doesn't work
Sorry for my English, I'm not a native speaker. If anyone could help me, that will be great.
Thanks.
var visible = true,
body = document.getElementById("body"),
mess = document.getElementById("message");
body.onclick = function() {
if (visible === true) {
mess.style.visibility = "hidden";
visible = false;
} else {
mess.style.visibility = "visible";
visible = true;
}
}
Edit Replaced body in selector as i didnt notice you wanted any part of the screen clicked
I'd suggest:
function toggleMessage(targetID){
var target = document.getElementById(targetID),
display = target.style.display;
target.style.display = display && display == 'block' ? 'none' : 'block';
}
document.body.addEventListener('click', function(){
toggleMessage('message');
});
Simple JS Fiddle demo.
Amended the above to use visibility (rather than display):
function toggleMessage(targetID){
var target = document.getElementById(targetID),
visibility = target.style.visibility;
target.style.visibility = visibility && visibility == 'visible' ? 'hidden' : 'visible';
}
document.body.addEventListener('click', function(){
toggleMessage('message');
});
Simple JS Fiddle demo.
References:
EventTarget.addEventListener().
Solution with jQuery (I recommend you to use display property. Because, if you use visibility, element will keep its space even it is hidden. With display: none; element is "removed".):
HTML
<div id="message"> Click! </div>
CSS
#message {
display: none;
}
jQuery
$(document).ready(function(){
$(window).click(function(){
$('#message').toggle();
});
});
DEMO: http://jsfiddle.net/j3KVT/2/
If you want to use visibility property then this is (one of many) solution with jQuery:
HTML
<div id="message">Click!</div>
jQuery
$(document).ready(function () {
$('#message').css('visibility', 'hidden');
$(window).click(function () {
if ($('#message').css('visibility') == 'hidden')
$('#message').css('visibility', 'visible');
else $('#message').css('visibility', 'hidden');
});
});
DEMO: http://jsfiddle.net/j3KVT/3/

Javascript toggle; trying to make it so initial div is not displayes

Hello: I am basically trying to have a toggle button (javascript) that when you click it a div appears and when you click it again the div disappears...
I found some code on here which basically does that; except the div is initially outputted on the page
(http://gerardsites.com/index)
I am new to learning javascript; and so I am trying to adapt this so that when page loads the div (gman123); is not shown; and then the button just toggles it...
here is the code:
<script type="text/javascript">
function toggleMe(btn, a) {
var e = document.getElementById(a);
if (!e) return true;
if (e.style.display == "none") {
e.style.display = "block";
btn.value = "MENU";
}
else {
e.style.display = "none";
btn.value = "MENU";
}
return true;
}
</script>
<input type="button" onclick="return toggleMe(this,'gman123')" value="MENU"><br>
<div id="gman123">
<br />
How about this for test text?
</div>
Can anyone help on this?
Thanks so much,
G
<html>
<body>
<script type="text/javascript">
function toggleMe(btn, a) {
var e = document.getElementById(a);
if (!e) return true;
if (e.style.display == "none") {
e.style.display = "block";
btn.value = "MENU";
}
else {
e.style.display = "none";
btn.value = "MENU";
}
return true;
}
</script>
<input type="button" onclick="return toggleMe(this,'gman123')" value="MENU">
<br>
<div id="gman123" style="display: none">
<br />
How about this for test text?
</div>
</body>
</html>
Add some CSS to hide the element initially...
Like so...
#gman123 {display:none}
your code is pretty fine. but since you wanna make this hidden on when the page load. so you have to hide it manually . Alternatively what you can do is call your function when page load is complete for that just add following code just before closing of your body Tag
<script type="text/javascript">
toggleMe(this,'gman123');
</script>
This will hide it for just one time . you can use this trick in future too.

hide div when click outside

I am using a simple javascript code to toggle div onclick. You can see it in action on this link: k-prim.biz/Untitled-2.html - it is a quite simple demo page. What I want to make is to hide div not only when click on the "link" but also when click outside the div. Also how can I change the css style of the "link" when the div is displayed? Thank you in advance!
<script type="text/javascript" language="javascript">
function showHide() {
var ele = document.getElementById("showHideDiv");
if(ele.style.display == "block") {
ele.style.display = "none";
}
else {
ele.style.display = "block"; }
}
</script>
<a href="#" onClick="return showHide();" >link</a>
<div id="showHideDiv" style="display:none;">hello!</div>
You've not given me any code to work with, so you'll have to modify this to suit your needs:
$(document).click(function() {
if(this != $("#the_div")[0]) {
$("#the_div").hide();
}
});
That will hide the div if a user clicks anywhere on the page that isn't that div.
HTML:
<div id="settings">
<input/><select></select><span>text</span>
</div>
Javascript:
var settings = document.getElementById('settings');
document.onclick = function(e){
var target = (e && e.target) || (event && event.srcElement);
var display = 'none';
while (target.parentNode) {
if (target == settings) {
display ='block';
break;
}
target = target.parentNode;
}
settings.style.display = display;
}
This is a quick hack I wrote. I am not sure why you want to do the same activity by clicking anywhere on the document. If you want to do that, replace jQuery('#link') with jQuery(document).
<html>
<head>
<script type="text/javascript">
$(document).ready(function(){
jQuery('#link').click(function(){
if(jQuery('#showHideDiv').hasClass('hide')) {
jQuery('#showHideDiv').removeClass('hide');
jQuery('#link').css('color', 'red');
} else {
jQuery('#showHideDiv').addClass('hide');
jQuery('#link').css('color', 'blue');
}
});
});
</script>
</head>
<body>
<a href="#" id="link" >link</a>
<div id="showHideDiv" class="hide">hello!</div>
</body>
</html>
This is the link to the jsfiddle
http://jsfiddle.net/EUScV/9/
and also add css rule
.hide {
display:none;
}

Categories

Resources