Target 2 divs for one method? - javascript

I have the following function:
$('#cover-drop-zone')[0].ondrop = function(e) {
How can I target two different divs with the above code? I want both divs to have the ondrop method.

Why not use jQuery:
$('#cover-drop-zone, #other-element-id').on('drop', function(e){
// do stuff here
});
Because your question isn't tagged with jquery, you could instead use plain JavaScript:
var elems = document.querySelectorAll('#cover-drop-zone, #other-element-id');
function dropFunction (e) {
// e is the event (passed automatically as the first parameter,
// this will refer to the element on which the function is called
// and whatever your function would/should do...
}
for (var i = 0, len = elems.length; i < len; i++){
elems[i].addEventListener('drop', dropFunction);
}
References:
on().

With this code :
$('#cover-drop-zone, #div2').bind('ondrop ', function(e) { })

Related

Converting jQuery Code to detect clicks on links with a specific class to Native JavaScript

ok so I can achieve what I am looking to do using jQuery very easily using the following code:
<script type="text/javascript">
// <![CDATA[
$('.pnTrig').on('click', function(e){
e.preventDefault();
var id = $(this).attr('href').split("_").pop(); // get last character of string
console.log(id); // check correct character is returned
P7_TP3ctrl('p7TP3_1',id); // controls to show accordian panels
});
// ]]>
</script>
What I would like is for someone to show me how to convert this jQuery code to native JavaScript please.
Here is a documented vanilla Javascript version.
function clickHandler(event) {
// execute preventDefault() if don't want the link to be followed (default browser behavior)
event.preventDefault();
// get the event target (what `this` would refer to in jQuery)
var target = event.target;
// same as before
var id = target.href.split('_').pop();
// same as before
P7_TP3ctrl('P7_TP3', id);
}
// get all elements with `pnTrig` class
var triggers = document.querySelectorAll('.pnTrig');
// apply the event handler to all matching elements
for (var i = 0; i < triggers.length; i++) {
// attach the event handler (don't define the event handling function here)
triggers[i].addEventListener('click', clickHandler, false);
}
function P7_TP3ctrl(label, id) {
console.log("Clicked id: ", id);
}
Link One
Link Two

Retrieving values from for loop into jquery

How do I retrieve values from #for loop into jquery..Each value inside for loop should have different id, and jquery should get each separate id....
My for loop,
#for (int i = 0; i < searchList.Count;i++ )
{
<label for="input#i"><input type="checkbox" id="input#i"/>#searchList[i] </label>
}
My jquery which isn't helping,
$("#input#i").on("click", function () {
var currentChk = $(this);
var propCheck = currentChk.prop("checked");
if (propCheck) {
debugger;
var valChk = $("#input#i").val();
alert(valChk);
}
});
Thanks in advance...
You can use Attribute Starts With Selector to bind the event.
$("[id^=input]").on("click", function () {
var currentChk = $(this);
var propCheck = currentChk.prop("checked");
if (propCheck) {
debugger;
var valChk = $("#input#i").val();
alert(valChk);
}
});
As the id of both label and input-checkbox starts with 'input' the click event will bind to both of them. If you want to restrict you can add type to the selector, for instance you want only on checkbox you can change selector as under.
$("input[id^=input]").on("click", function () {...
or
$(":checkbox[id^=input]").on("click", function () {...
If you assign a class to the control you want to attach event then you can use class selector to bind the event.
#for (int i = 0; i < searchList.Count;i++ )
{
<label for="input#i"><input type="checkbox" class="chk-class" id="input#i"/>#searchList[i] </label>
}
$(".chk-class").on("click", function () {...
Edit As Mohamed-Yousef pointed you should use currentChk preferably or $(this) instead of $("#input#i") in statement $("#input#i").val(); as #i will not be the substituted value by C# loop but it will be added as string literal.
As a additional note you may use native javascript whenever possible and suitable e.g I would use this.checked instead of currentChk.prop("checked") to get the better performance, readability and simplicity.
$("[id^=input]").on("click", function () {
if (this.checked)
{
//your code
}
else
{
//your code
}
});
if you want to trigger onclick for all input
$("input").click(function () {
var currentChk = $(this);
var propCheck = currentChk.prop("checked");
if (propCheck) {
var valChk = "Id:" + this.id + " Value:" + this.value;
alert(valChk);
}
});
$("input:checkbox [id^=input]").click(function(){
if ($(this).is(":checked")) {
var valChk = $("this").val();
alert(valChk);
}
});
this another option you can use

How to get a variable's literal value when setting an element's onclick handler via jQuery? [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 8 years ago.
Is there a way to be able to get the literal value passed into the click() function?
<script>
var texts = ['t1', 't2', 't3', 't4', 't5'];
$(document).ready(function () {
for (var i = 0; i < texts.length; i++) {
var div = $("<div>");
div.click(function () {
div.text(texts[i]); // <---- problem here
console.log(texts[i]); // with texts[i]
});
$("#container").append(div);
}
});
</script>
<div id="container"></div>
Intended result:
5 div elements each respectively containing the text "t1", "t2", etc.
5 div elements each, when clicked on, output the text "t1", "t2", etc. to the console.
Alternate Solution 1:
$(document).ready(function () {
for (var i = 0; i < texts.length; i++) {
var div = $("<div>");
div.click({index: i}, function (e) {
div.text(e.data.index);
console.log(e.data.index);
});
$("#container").append(div);
}
});
Alternate Solution 2:
A function can be added to set the text in the onclick event handler :
function setClick(elem, text) {
elem.click(function () { console.log(text); });
}
So that div.click( ... ); is replaced by:
setClick(div, i);
The problem is when you click the div, at that time value of i is 5, so for that you will not get any result. You should used IIFE and wrap click call in this function. Like this
$(document).ready(function () {
for (var i = 0; i < texts.length; i++) {
var div = $("<div>");
div.click((function () {
div.text(texts[i]); // <---- problem here
console.log(texts[i]);
})(i));
$("#container").append(div);
}
});
You don't need to add click handler for assigning text property before appending.
Also you should not attach the same event in loop. bind single event that should work for all of them. which can be achieved in two ways:
1) either bind the click event after appending
2) or use event delegation.
for (var i = 0; i < texts.length; i++) {
var div = $("<div>");
div.text(texts[i]); // <---- problem here
console.log(texts[i]);
$("#container").append(div);
}
$("#container div").click(function(){
console.log($(this).text());
});
Working Demo

Javascript every href onclick

I am developing an app that stays in the website itself, and I want every link to call a function. I have tried this:
HTML
link<br>
link 2
Javascript
var a = document.getElementsByTagName("a");
for (var i = 0; i < a.length; i++) {
a[i].onclick = function () {
return false
}
}
What is wrong? It doesn't work.
Since it's not jQuery, you should use the preventDefault function.
var a = document.getElementsByTagName("a");
for (var i = 0; i < a.length; i++) {
a[i].onclick = function (e) {
e.preventDefault();
doSomething();
}
}
edit for pure javascript solution
document.addEventListener("click", function(e){
if (e.nodeName==="A"){
e.preventDefault();
return false;
}
}, false);
This will only add one single event to the document and prevent all clicks on anchor elements only.
I removed the old solution because of the comment, that this wasn't a jquery question
Don't use return false, it does more than you really need. Instead try event.preventDefault()
var a = document.getElementsByTagName("a").forEach(function (e) {
e.onclick = function (a) {
doSomething(a);
return false;
}
}
}

Get clicked class index javascript

I have 3 divs with class: wpEdit and onClick: alertName()
<div class="wpEdit" onClick="alertName()">Bruce Lee</div>
<div class="wpEdit" onClick="alertName()">Jackie Chan</div>
<div class="wpEdit" onClick="alertName()">Jet li</div>
When clicked i want to know the Index of class wpEdit of the clicked Div:
function alertName(){
//Something like this
var classIndex = this.className.index; // This obviously dosnt work
alert(classIndex);
}
when clicked on Bruce Lee it should alert : 0
when clicked on Jackie Chan it should alert : 1
when clicked on Jet Li it should alert : 2
I need to know which instance of class="wpEdit" is clicked on
Try this
function clickedClassHandler(name,callback) {
// apply click handler to all elements with matching className
var allElements = document.body.getElementsByTagName("*");
for(var x = 0, len = allElements.length; x < len; x++) {
if(allElements[x].className == name) {
allElements[x].onclick = handleClick;
}
}
function handleClick() {
var elmParent = this.parentNode;
var parentChilds = elmParent.childNodes;
var index = 0;
for(var x = 0; x < parentChilds.length; x++) {
if(parentChilds[x] == this) {
break;
}
if(parentChilds[x].className == name) {
index++;
}
}
callback.call(this,index);
}
}
Usage:
clickedClassHandler("wpEdit",function(index){
// do something with the index
alert(index);
// 'this' refers to the element
// so you could do something with the element itself
this.style.backgroundColor = 'orange';
});
The first thing you might want to address in your code is the inline HTML binding.
You could use document.addEventListener on each element, or rely on event delegation.
The widely most used implementation of event delegation comes with jQuery. If you're already using jQuery, this is the way to go!
Alternatively I've also my own little delegate utility.
const delegate = (fn, selector) => {
return function handler(event) {
const matchingEl = matches(event.target, selector, this);
if(matchingEl != null){
fn.call(matchingEl, event);
}
};
};
const matches = (target, selector, boundElement) => {
if (target === boundElement){
return null;
}
if (target.matches(selector)){
return target;
}
if (target.parentNode){
return matches(target.parentNode, selector, boundElement);
}
return null;
};
This is how you would register the event listener.
document.getElementById('#parent')
.addEventListener('click', delegate(handler, '.wpEdit'));
And this is how you could get the index of the element that generated the event.
const handler = (event) => {
console.log(Array.prototype.indexOf.call(event.currentTarget.children, event.target));
}
Live demo:
const delegate = (fn, selector) => {
return function handler(event) {
const matchingEl = matches(event.target, selector, this);
if (matchingEl != null) {
fn.call(matchingEl, event);
}
};
};
const matches = (target, selector, boundElement) => {
if (target === boundElement) {
return null;
}
if (target.matches(selector)) {
return target;
}
if (target.parentNode) {
return matches(target.parentNode, selector, boundElement);
}
return null;
};
const handler = (event) => {
console.log(Array.prototype.indexOf.call(event.currentTarget.children, event.target));
}
document.getElementById('parent')
.addEventListener('click', delegate(handler, '.wpEdit'));
<div id="parent">
<div class="wpEdit">Bruce Lee</div>
<div class="wpEdit">Jackie Chan</div>
<div class="wpEdit">Jet li</div>
</div>
If you want the index of the div's based on your class wpEdit you can do like this:
HTML:
<div class="wpEdit">Bruce Lee</div>
<div class="wpEdit">Jackie Chan</div>
<div class="other">Other</div>
<div class="wpEdit">Jet li</div>
JS:
$(".wpEdit").bind("click", function(){
var divs = $(".wpEdit");
var curIdx = divs.index($(this));
alert(curIdx);
});
Live example : http://jsfiddle.net/pJwzc/
More information on the index function of jQuery : http://api.jquery.com/index/
Using vanilla javascript, this one works for me:
var wpEdits = document.querySelectorAll(".wpEdit");
for (let i = 0; i < wpEdits.length; i++)
wpEdits[i].addEventListener("click", showID);
function showID(evt) {
for (let i = 0; i < wpEdits.length; i++)
if(wpEdits[i] == evt.target)
alert(i);
}
May not be the best solution though as I am still new to js.
Since I am very new to JS, take the following explanation with a grain of salt:
(Line-1)
This is similar to var wpEdits = document.getElementsByClassName("wpEdit");. It will assign all instances of class="wpEdit" from the html file to the wpEdits variable.
(Line-3 and Line-4)
This two lines will cause any click on the class="wpEdit" to call function showID() defined below.
(Line-6 and Line-10)
When a click event happens, the browser will pass the unique properties of the item being clicked to the evt variable. This then is used in the for loop to compare against all available instances incrementally. The evt.target is used to get to the actual target. Once a match is found, it will alert the user.
To avoid wasting CPU time, running a break; is recommended to exit the loop soon after the match is found.
I could not understand, why people add new functions in previous answers, so...
const wpEdit = document.getElementsByClassName('wpEdit');
for(let i = 0; i < wpEdit.length; i++){
wpEdit[i].addEventListener('click',function(){
alert(i);
});
}
I just added 'click' event, using the loop. And [i] already is the current clicked class index...
FIDDLE

Categories