I have a mobile web gallery page where I have a CSS floated "next" link. The CSS float property causes the link to have a display: block behavior on it. A jQuery touchstart event is bound to the link. When the user clicks on the link, the Javascript code bound to that touchstart event advances the gallery by one slide via Ajax. In other words, there is no page refresh.
However, I noticed that occasionally when I touch an area of the link's block space that is not the link text itself, the browser follows the href and causes a page refresh (because the URL has changed) instead of executing the Javascript code bound to the touchstart event.
Has anybody seen this before? Is there a way to fix this?
I simplified it down to this code below, and it still happens, although much less frequently.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
<title>Test</title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.js'></script>
<style type='text/css'>
.cont { width: 320px; }
.next { border-left: 1px solid #000; float: right; text-align: right; width: 65px; }
.msg { clear: both; width: 200px; }
</style>
<script type='text/javascript'>//<![CDATA[
$(function(){
$('.next').bind('click touchstart', function(event) {
event.preventDefault();
if (event.type == 'touchstart') {
$(this).unbind('click');
}
$('.msg').append('<p>Click!</p>');
});
});//]]>
</script>
</head>
<body>
<div class="cont">Next</div>
<div class="msg"></div>
</body>
</html>
I tested this on my iPhone and it seems to work. For some reason after registering a touchstart event you are unbinding the click events. Is there any reason for that?
When you click on the text of the link all it seems to register is indeed touch start, so unbinding click does not break things. I do believe, however, that when you touch outside the text link, but still within the block space it registers both a touchstart and click, so at this point you have already unbound click and it works as a regular link.
You should notice, that on your first click outside the bounds it never goes to yahoo.com. It's only the subsequent once that do that.
So in essence what you need to do is remove that unbind, as so:
<script type='text/javascript'>//<![CDATA[
$(function(){
$('.next').bind('click touchstart', function(event) {
event.preventDefault();
$('.msg').append('<p>Click!</p>');
});
});//]]>
</script>
Is there any reason why you would want to unbind click?
Related
HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<div class="testdiv">
<button type="button"></button>
</div>
<body>
<html>
CSS:
button {
background-color: skyblue;
height: 75px;
width: 150px;
border-radius: 5px;
}
JavaScript:
const testdiv = document.querySelector('.testdiv');
document.addEventListener('click', (event) => {
console.log('I was clicked');
});
Open your console, now click the blue button. Then press the Enter key. Notice how the keypress caused the button to click. Now, click it again, but this time click in the white space afterwards and then press Enter. Notice that nothing is logged in the console.
Why does the enter key cause an element to be clicked after the element has been selected with the mouse, and how do you disable this feature?
If I wanted to map a keydown or keyup event for the Enter key to a different element without the console being logged in this program, I would have a serious problem.
I'm not sure the cause of this behavior. I noticed Tab exhibits a weird behavior too where if multiple elements are present and one is selected by the mouse, you can press Tab and it will select the next element. This doesn't bother me, but it's another example of these pre-bound key behaviors that I would like to be able to disable.
Try setting the property tabindex=-1 on the divs, that should help.
I am very new to JavaScript, jQuery and HTML etc. And I am supposed to implement this block of code (below) in a project and I am not quite sure what it is meant to do:
$(document).ready(function(){
$("body").click(function(){
$(this).hide();
});
});
I'm assuming it simply hides any element that is clicked.
You are correct, it hides everything inside of the HTML element. It is also important to note that it is written using jQuery, which is a JavaScript library that has helper functions to make JavaScript more accessible to use.
Here is one line at a time:
Wait for the page to finishing loading in the browser (aka the DOM, or document object model):
$(document).ready(function(){
});
When the user fires the click event on the body element, run the following function:
$("body").click(function(){
});
Hide the body:
$(this).hide();
this (in this context) refers to the body element targeted in the previous line, this is the same as writing: `$('body').hide();
this refers to something different based on the context in which it is used. In this example it is used in an event, so it refers to the element that received that event (body). See W3Schools.
.hide() is a built in jQuery function that sets the element to display: none;
$(document).ready is called when the page is ready for javascript to be executed. $("body") selects the body, the body of the document is where all of the visible HTML elements are shown. The click event is triggered when well, the element is clicked. $(this) selects the current element being operated on, which is the body. the hide function hides the selected element, which in this case is the body. So this code hides the body of the HTML page resulting in all visual elements being hidden.
It's simple, it puts an "on click" event on the body element.
So that means, when you click the body element. It will hide everything in between the opening <body> and the closing </body> tags
<body>
<!--everything in here will be hidden once body element is clicked-->
</body>
That code will make it so that clicking on any element on the page will cause the body element to hide.
That is - unless the element has it's own onclick functionality assigned that stops the event from bubbling up to the body element's onclick by using the event.stopPropagation() function.
Note: You could also have a call to event.stopPropagation() within the event handler rather than just having it as the event handler.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("body").click(function() {
$(this).hide();
});
});
</script>
<html>
<head>
<title>Testing javascript function</title>
</head>
<body>
<p>Here is one paragraph</p>
<p>Here is a second paragraph</p>
<p>Clicking on any element will hide the entire body element.</p>
<input type="button" value="random button" onclick="event.stopPropagation()" />
</body>
</html>
It is pretty straight forward.
Sample HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
...
</body>
</html>
Js:
$(document).ready(function(){ //executes when document model is ready
$("body").click(function(){ //once u click anywhere on the page this function will be executed
$(this).hide(); //hides everything between <body></body>
});
});
I got a page I got a link. The link goes to http://stackoverflow.com.
In addition, click anywhere on the link and it goes to http://stackoverflow.com too.
I am just curious. Is there a way to do so without writing stackoverflow.com twice?
Can I make the link in the link to be inactive and clicking the link means the user activate the code written in "onclick" on body?
This is the code:
<!doctype HTML>
<html>
<head>
<meta content="en-us" http-equiv="Content-Language" />
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Title</title>
<style>
#centerInScreen {
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
}
#centerInScreen h1 {
position: relative;
top: 50%;
transform: translateY(-50%);
}
.auto-style1 {
text-align: center;
}
</style>
</head>
<body onclick="window.location.replace('http://stackoverflow.com');">
<div id="centerInScreen">
<h1 class="auto-style1">
Click here to Get Game and See Yourself</h1>
</div>
</body>
</html>
You can see the code in action here
http://romancepriorities.com/test/index2.html
Basically the link is part of the body. So I want body.onclick to be called when a user click the link.
You could give your a element an id, and then when the click event happens, you would get the element by that id, and call the click method on it:
<body>
<div id="centerInScreen">
<h1 class="auto-style1">
<a id="go" href="http://stackoverflow.com">Click here to Get Game and See Yourself</a>
</h1>
</div>
<script>
document.addEventListener('click', function() {
document.getElementById('go').click();
});
</script>
</body>
Note that as you had it, the behaviour was not the same: location.replace will not generate an entry in the browser history, so you cannot go back. Also, the body element does not necessarily fill the page, so not all clicks would be detected, like is the case with listening to the event on document.
Two-step link
If you want to have the link "inactive" until it is clicked, and only then allow a navigation to happen on a second click anywhere on the page, then use a variable:
<body>
<div id="centerInScreen">
<h1 class="auto-style1">
<a id="go" href="http://stackoverflow.com">Click here to Get Game and See Yourself</a>
</h1>
</div>
<script>
document.addEventListener('DOMContentLoaded', function () { // after doc loaded
var hasClicked = false;
var go = document.getElementById('go');
document.addEventListener('click', function() {
// only when link was activate with previous click
if (hasClicked) go.click();
});
go.addEventListener('click', function() {
if (!hasClicked) { // not yet clicked before?
// log the fact that the link was clicked
hasClicked = true;
// but cancel the navigation
return false;
}
});
});
</script>
</body>
You would need to use some visual hints so this becomes user-friendly: with classes you could make the link "look" inactive until it receives its first click. Upon that click you could change the style, and maybe its text,...etc. But this goes beyond the question.
I want a window to close only when pop_up is clicked (as opposed to clicking div contents). E.g. clicking the background layer hides the div. In the code below I don't want it to close #pop_up when clicking the div contents bot only on "pop_up".
How can I do this?
$("#pop_up").click(function() {
$("#pop_up").hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pop_up">
<div id="pop_up_content">
<h1> world </h1>
</div>
</div>
What you are experiencing is the bubbling and capturing behaviour of events.
Check this answer What is event bubbling and capturing? .
The simples approach would be to attach a onClick to the child and stop the bubbling.
$("#pop_up_content").click(function(ev) {
ev.preventDefault()
ev.stopImmediatePropagation() // best to use to stop other event listeners from being called
});
You can use the event argument of the click, and see if the click is inside another element (or it is the element itself)
JSFiddle: https://jsfiddle.net/32mz2x3x/1/
$("#pop_up").click(function(event) {
if ($(event.target).parents().andSelf().is('#pop_up_content')) {
return
}
$("#pop_up").hide();
});
I have used parents to check if where you click is inside pop_up_content element, and I used andSelf because maybe you click on #pop_up_content (and not inside it)
More info:
jQuery andSelf function
jQuery is function
jQuery parents function
jQuery event object
use the form that allows a filter selector, combined with :not():
$("#pop_up").on('click', ':not(#pop_up_content)', function (e) {
$("#pop_up").hide();
});
JSBin: http://jsbin.com/hoyizos/edit?html,css,js,output
$("#pop_up").click(function(e) {
if ($(event.target).is($("#pop_up"))){
$("#pop_up").hide();
}
});
h1{
margin:50px 50px;
background-color:red;
display:inline;
}
#pop_up_content{
background-color:yellow;
}
#pop_up{
margin:10px;
background-color:green;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://code.jquery.com/jquery-3.0.0.js"></script>
</head>
<body>
<div id="pop_up">
<div id="pop_up_content">pop_up_content
<h1> world </h1>
</div>
I am the pop_up!
</div>
</body>
</html>
Don't cancel event bubbling!: The Dangers of Stopping Event Propagation, use it only if there is no other way.
Don't use andSelf() if you plan to use jQuery 3.x, because it is deprecated since v1.8 and will be removed in jQuery v3.
Note: This function has been deprecated and is now an alias for
.addBack(), which should be used with jQuery 1.8 and later.
If you use jQuery 1.8 < use addBack instead.
I am using phonegap to build android apps.
I would like to detect the touch event from a user so I can pop-up an alert. However, how do I call the ontouch event from javascript?
Thanks!
Below is an example that shows touchstart and touchend. It demonstrates two different ways to attach touch events: element attributes or JavaScript's addEventListener.
Since it is listening for touch events, the events will not fire on a desktop browser (which supports mouse events). To test the page, you can open it a Android or iOS simulator.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0;" />
<style type="text/css">
a {
color:black;
display:block;
margin:10px 0px;
}
</style>
<script type="text/javascript">
function onload() {
document.getElementById('touchstart').addEventListener('touchstart', hello, false);
document.getElementById('touchend').addEventListener('touchend', bye, false);
}
function hello() {
alert('hello');
}
function bye() {
alert('bye');
}
</script>
<title>Touch Example</title>
</head>
<body onload="onload();">
<h1>Touch</h1>
Attribute: ontouchstart
Attribute: ontouchend
addEventListener: touchstart
addEventListener: touchend
</body>
</html>