How to exclude div from firing this event? - javascript

I use code bellow to get the text that user has double clicked:
<html>
<script language="javascript">
document.ondblclick = function() {
alert(GetSelectedText());
}
function GetSelectedText() {
if (document.selection) {
return document.selection.createRange().text;
}
}
</script>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
</head>
<body>
<div id="should_trigger_event">sample of a text!</div>
<div id="should_not_trigger_event">sample of a text!</div>
</body>
</html>
I want to ondblclick event just fire up for div with id: should_trigger_event and not for div with id: should_not_trigger_event
How can we achieve that?

It is simple using jQuery :
<script language="javascript">
$(document).ready(function(){
$('#should_trigger_event').on('dblclick',function(){
alert(GetSelectedText());
});
});
function GetSelectedText() {
if (document.selection) {
return document.selection.createRange().text;
}
}
</script>
More Information on
jQuery Selectors
jQuery double click binding

Why dont you bind click event using element id:
$(function(){
$('#should_trigger_event').click(function(){
if (document.selection) {
return document.selection.createRange().text;
}});});

You can directly assign the handler to the div you want to include…
var div = document.getElementById('should_trigger_event');
div.ondblclick = function() {
alert(GetSelectedText());
}
or if you want the handler for whole document, you can check target in event object
document.ondblclick = function(e) {
if(e.target.id != 'should_not_trigger_event')
alert(GetSelectedText());
}

Related

Drag n Drop using JavaScript

I have begun to learn JavaScript. I have tried the following to drag and drop an image into a dropzone called "dropTarget1"; the image is not draggable. Can you please take a look at my code and advise what I am doing wrong.
var draggable=document.getElementById('dragMe1');
draggable.addEventListener('dragstart',dragStart,false);
var droptarget=document.getElementById("dropTarget1");
droptarget.addEventListener('dragenter',dragEnter,false);
droptarget.addEventListener('dragover',dragOver,false);
droptarget.addEventListener('dragleave',dragLeave,false);
droptarget.addEventListener('drop',drop,false);
function dragStart(event){
event.dataTransfer.setData('text/html', event.currentTarget.id);
}
function dragOver(event) {
event.preventDefault();
return false;
}
function drop(event) {
var dragMe1=document.createElement("img");
var data = event.dataTransfer.getData('text/html');
event.preventDefault();
event.stopPropagation();
dragMe1.src=data;
droptarget.appendChild('dragMe1');
return false;
}
#dropTarget1{
width:300px;
height:300px;
background-color:#DBF272;
}
#dragMe1{
width:300px;
}
#dragMe1 img{
padding-left:45px;
}
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<link href="myStyle.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="dropTarget1"></div>
<img id="dragMe1" src="logo1.png" draggable="true" >
<script src="myDragnDrop.js"> </script>
</body>
</html>
If you want to use jQuery, then this Draggable|jquery UI can be a really simlple option.
Your JavaScript code should be like this (Explanation in the comments);
var draggable=document.getElementById('dragMe1');
var droptarget=document.getElementById("dropTarget1");
var newIm = document.createElement("img"); //Create new image element
/*Subscribe to dragover event.
This event fires when a user drag the image over the target */
droptarget.addEventListener('dragover',dragOver,false);
/*Subscribe to drop event.
This event fires when a user drop the image on the target */
droptarget.addEventListener('drop',drop,false);
function dragOver(event) {
event.stopPropagation(); //Prevent further drop events from bubbling up the DOM tree
event.preventDefault(); //Prevent the default behavior of the browser when dropping something on it
event.dataTransfer.dropEffect = "move"; //Specify the feedback that the user receives when a user drags over the target. It can be copy, link, or none
return false;
}
function drop(event) {
var data = event.dataTransfer.getData('text/plain'); //To retrieve the image URL
event.preventDefault();
event.stopPropagation();
newIm.src=data; //Write the image URL into the src attribute of newIm
droptarget.appendChild(newIm); //Add the new created image to the target element
document.body.removeChild(draggable); //Remove the original image as you're dragging and dropping (moving)
return false;
}
You don't have to subscribe to some events like dragenter, you just need to subscribe to dragover and drop events.

JavaScript focus() function doesn't focus textarea on page load

I have the following code.
<!DOCTYPE html>
<html>
<head>
<title>Focus issue</title>
<script type='text/javascript'>//<![CDATA[
window.onload=function(){
var text = document.getElementById('text')
window.onload = function() {
text.focus()
}
window.onhashchange = function() {
text.focus()
}
}//]]>
</script>
</head>
<body>
<textarea id="text"></textarea>
<p>Click to focus</p>
</body>
</html>
Here is a JSFiddle demo of the above code: http://jsfiddle.net/DvU63/
Why doesn't the focus go on the textarea box when the page loads? On clicking the link, the focus does go on the textarea box, but I also want the focus to go to the textarea box on page load. Why doesn't it happen?
Note: I am aware of the HTML5 autofocus attribute for textarea. But this question is about why the above JavaScript code does not do what I intend to do.
You're doing the .focus() statement from inside an onload handler that is itself defined inside an onload handler. This inner onload will not be called because by the time you define it the onload event will have occurred. Try this:
window.onload=function(){
var text = document.getElementById('text')
text.focus()
window.onhashchange = function() {
text.focus()
}
}
Your demo, updated: http://jsfiddle.net/DvU63/2/
do this
<script type='text/javascript'>
window.onload=function(){
var text = document.getElementById('text')
text.focus();
window.onhashchange = function() {
text.focus();
}
}
</script>
fiddle

html body ondblclick get clicked element

so in my html i have this portion:
<body ondblclick="myfunc();">
<div id="id1">dasd</div>
<div id="id2">dasda</div>
</body>
and in javascript the function is :
function myfunc() {
do stuff here...
}
i want to know inside myfunc() on which element of the html body the doubleclick was made, because i don't want to triger myfunc() on every doubleclicked element
so how can i detect the id of the element doubleclicked?
<body ondblclick="myfunc(event);">
function myfunc(e) {
// e.target -> element that was clicked
}
make your HTML as
<body ondblclick="myfunc(event);">
and make myfunc as:
function myfunc(event) {
alert(event.target.id); //here you can get element id that is double clicked
event.stopPropagation();
}
<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>ondblclick event example</title>
<script>
function initElement() {
var body = document.getElementById("bdy");
body.ondblclick = showAlert;
}
function showAlert(e){
alert(e.target.id);
}
window.onload = initElement;
</script>
</head>
<body id="bdy">
<div id="id1">dasd</div>
<div id="id2">dasda</div>
</body>
</html>
you can define different events with use of on or bind suppose..
$("#id").on("doubleClick",function () {} );
so it will know that its double click event..
or for javascript you can use like this
<body ondblclick="myfunc(event);">
function myfunc(event) {
do something..
}

dynamically create element using jquery

I am trying to create element using jquery. When i click on a link, i want to create an element "p", give it some text, and then put it in one of my divs. Also, i want to check which link is clicked on, so i can put the created "p" in the right div. Any solutions on where i am doing it wrong?
Javascript/Jquery
$(document).ready(function () {
function createElement() {
var a = $("#menu").find('a').each(function(){
if(a == "l1"){
var text = $(document.createElement('p');
$('p').text("Hej");
$("#contentl1").append("text");
}
});
}
$("#menu").find('a').each(function () {
$(this).click(function () {
createElement();
});
});
createElement();
});
HTML
<html>
<head>
<title>Inl1-1</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="style-1.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="Uppg1.js"></script>
</head>
<body>
<ul class="meny" id="menu">
<li>Utvärdering/Feedback</li>
<li>Kontakt</li>
<li>Öppettider</li>
<li>Om Asperöd</li>
</ul>
<div id="contentl1">
</div>
<div id="contentl2">
</div>
<div id="contentl3">
</div>
<div id="contentl4">
</div>
</body>
</html>
Here is the best way to add new <p> element with text "Hej" to #contentl1 using jQuery:
$("<p />", { text: "Hej" }).appendTo("#contentl1");
function createElement() {
var a = $("#menu").find('a').each(function(){
if(a == "l1"){
var p = $("<p>");
p.text("Hej");
$("#contentl1").append(p);
}
});
}
For a start the click function can be done like this instead of having to use .find():
$('#menu a').click(function() { }
The .each() loop can be done like:
$('#menu a').each(function () {
var aId = $(this).attr('id');
var contentId = content + aId;
$(contentId).append('<p>Hej</p>');
})
I know it doesn't realate to answering your question but it is hard to leave this as a comment:
var a = $("#menu").find('a').each(function(){ <-- this "a" will only be created after the each completes
if(a == "l1"){ <-- this "a" that you are verifying is a global variable
var text = $(document.createElement('p');
$('p').text("Hej");
$("#contentl1").append("text");
}
});
You can try this to solve your issue:
function createElement() {
if($(this).attr("id") == "l1"){
$("#contentl1").append('<p>hej</p>');
}
}
$("#menu a").each(function () {
$(this).click(function () {
createElement.apply(this);
});
});
Something like this fiddle?
$('#menu').on('click', 'a', function(e) {
e.preventDefault();
$('<p>').text($(this).text()).appendTo('#content'+this.id);
});
try this script, it'll do place the text in correct div.
$(document).ready(function () {
$("#menu").find('a').each(function () {
$(this).on('click',function () {
$("#content"+$(this).attr("id")).append("<p>link "+$(this).attr("id")+" is clicked</p>");
});
});
});
I personally like to use classic JS DOM for tasks so this is how you can first create the DOM object using JQuery. The DOM object returned is the outer element of HTML (p tag) but the inner HTML can be as complex as you want.
var elP = $("<p>Hej</p>")[0]
// Do some other DOM manipulations of p
// eg: elP.someCustomTag='foobar'
$("#content1").append(elP)

jQuery - who really clicked me?

I have this jsbin ( prev answers didn't help much)
 
<span id="mySpan" > click here </span>
  <br/> 
  <input id="myCb" type="checkbox"/>
i have a listener for checkbox click which do Alert...
However , clicking on the span is triggering the click event for the checkbox.
I want to detect - who really made the checkBox execute the alert.
But !
I want :
if first clicked the span , alert
i was originally pressed by mySpan
else
if first clicked the checkbox , alert i was originally pressed by myCb
$("#mySpan").on('click',function (e)
{
$("#myCb").trigger('click');
});
$("#myCb").on('click',function (e)
{
doWork(e)
});
function doWork(e)
{
alert('i was originally pressed by '+$(e.delegateTarget).attr('id') );
}
p.s. i can use a global field or flag solution - which i DONT WANT.
i will be glad to have a "moving the data" through the e param - solution.
thanks.:)
edit
jQuery does support moving data , but i cant write the right code
This works for me,
<html>
<head>
<style>
</style>
<script src='jquery.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
$("#mySpan").on('click',function (e){
$("#myCb").trigger('click','span');
});
$("#myCb").on('click',function (e,span){
var ele = span || 'cb';
doWork(ele);
});
function doWork(ele){
alert('i was originally pressed by ' + ele );
}
})
</script>
</head>
<body>
<span id="mySpan" style="width:100px;height:100px;" > click here </span>
<br/><br/><br/>
<input id="myCb" type="checkbox"/>
</body>
</html>
Fiddle
how about this.
$("#mySpan").on('click',function (e)
{
$("#myCb").trigger(e);
});
$("#myCb").on('click',function (e)
{
doWork(e);
});
function doWork(e)
{
alert('i was originally pressed by '+$(e.target).attr('id') );
}
It worked for me and it was the closest to your original code.
in action http://jsbin.com/ixanup/2/edit#javascript,html
$("#mySpan, #myCb").on('click', function (e) {
alert('I was originally pressed by ' + e.target.id);
console.log($(e.target)); /* jQuery reference to the clicked element */
if (e.target.id === 'myCb') {
/* do code only if checkbox was clicked */
}
});
Example fiddle: http://jsfiddle.net/4AVZz/
maybe this code helpful for you:
$("#mySpan").on('click',function (e)
{
alert('i was originally pressed by '+$(e.delegateTarget).attr('id') );
if($("#myCb").attr('checked')=="checked")
$("#myCb").removeAttr('checked');
else
$("#myCb").attr('checked','checked');
});
$("#myCb").on('click',function (e)
{
alert('i was originally pressed by '+$(e.delegateTarget).attr('id') );
});
$("#mySpan").on('click',function () {
var cb = $("#myCb");
if(cb.is(':checked')) {
cb.removeAttr('checked');
} else {
cb.attr('checked', true);
}
doWork.apply($(this));
});
$("#myCb").on('click',function (e) {
doWork.apply($(this));
});
function doWork(e) {
console.log('i was originally pressed by '+$(this).attr('id') );
alert('i was originally pressed by '+$(this).attr('id') );
}
I've modified your example as per your requirement. And saved as a new version.
Please have a look at this. http://jsbin.com/axaqer/7/edit
I would do something like this:
$(function() {
$('.row span, .row input[type="checkbox"]')
.on('click', function (evt) {
triggerCheckbox($(this), evt.currentTarget.tagName);
doWork(evt.currentTarget.tagName);
});
});
function doWork(elm) {
// elm with either be INPUT or SPAN
console.log('I was originally pressed by ' + elm);
}
function triggerCheckbox(elm, evt) {
// if it's a SPAN, let's change the checkbox value without
// triggering the click event
if(evt.currentTarget.tagName === 'SPAN') {
var ckb = $(elm).closest('.row').find('input[type="checkbox"]');
$(ckb).prop('checked', !$(ckb).prop('checked'));
}
}
and it will not matter what ID you have, it will work with all, as long as you have a wrapper grouping the both.
in HTML, I added a <div> to wrap your content, so it will look like:
<div class="row">
<span id="mySpan">click here</span>
<br/><br/><br/>
<input id="myCb" type="checkbox"/>
</div>
live example can be found on JsBin as well.
why dont you use,
e.currentTarget
?

Categories

Resources