This must be a simple one for expert. I am new to JS/jQuery. I have got a script to drag and copy and I modified it according to my requirements. It is implemented with "id" selectors. I want to implement the same using "class" selectors.
Here is the fiddle demo
$(document).ready(function(){
$('#arsenal').on("dragstart", ( function (e) {
e.originalEvent.dataTransfer.setData("Text", e.target.id);
}));
$('#leftbox').on("dragenter", ( function (e) {
e.preventDefault();
}));
$('#leftbox').on("dragover", ( function (e) {
e.preventDefault();
}));
$('#leftbox').on("drop", ( function (e) {
e.preventDefault();
$(this).empty();
var data=e.originalEvent.dataTransfer.getData("Text");
var nodeCopy = document.getElementById(data).cloneNode(true);
nodeCopy.id = "newId";
e.target.appendChild(nodeCopy);
}));
});
Explanation:
I have a requirement where I need to implement this for a set of images which are dynamically added(with JS). So I cannot use Id of the target images. I need to use class. I tried but couldn't get it working.
Can anyone help me with this?
Thanks in advance,
Here's a basic JSFiddle of what you're doing using classes.
It's pretty much a matter of changing your selctor:
$('.draggableImg').on("dragstart", ( function (e) {
...
});
There's also a minor problem -- if you have dragged an image to the leftbox, and then drag the image in leftbox to leftbox... you'll get an error. (You might just need to removeClass after copying the image to leftbox).
Alterantively, if you're saying that your elements won't have ID's... then you'll need to pass around the actual source of the image, rather than the element ID. Here's an updated fiddle which does that.
And here's one where you always append to the box, rather than to the target (which may be the img which has just been cleared)!
Use something like '.js-drag-item' and '.js-drop-target' to replace your div id's. I like to add 'js-' so I remember it is a class name that has Javascript associated with it rather than CSS.
e.g.
JS
$('.js-drag-item').on("dragstart", ( function (e) {
e.originalEvent.dataTransfer.setData("Text", e.target.id);
}));
HTML
<section class="js-drag-item">
....
</section>
<section class="js-drag-item">
....
</section>
etc
You can have as many drag items or drop items as you want and the JS will be applied to all of them
Class selector (".class") selects all elements with the given class. An element can have multiple classes; only one of them must match.
So simply replace ids with clas selectors, like this:
$('.class').on("dragstart", ( function (e) {
e.originalEvent.dataTransfer.setData("Text", e.target.id);
}));
Related
I am trying to limit query calls using a function that will place edited items into an object then pass them to a PHP script to update only the edited information. In this case I am using jQuery's change() function, however I can not find a pseudo selector for select menu's (ie. :input, input:checkbox). The only idea I have left is to add a class to all the select menu's and go from there like so:
$(":input, input:checkbox, .selectedMenu").change(function() {
//Some Code here
});
I have checked all over and cannot find any information on this. Would this be the best way or is there an alternative?
Problem: How can you find out if any select menu has been put into focus using a pseudo selector or anything on those lines?
Select is its own tag. You don't need a psuedoselector:
$("select").change(function () { ... });
I think that all you want to do is use the select box that was changed, in this case you can do this
$(":input, input:checkbox, .selectedMenu").change(function() {
var $el = $(this);
alert($el.val());
});
you can add a focused class:
$(":input, input:checkbox, .selectedMenu").change(function() {
$(".focused").removeClass("focused");
this.addClass("focused");
//Some Code here
});
I would put this as a comment but I'm not allowed to... Maybe I misunderstood your question, but what about:
$(":input, input:checkbox, select")
I'm using a javascript function to set the value of a text field, based on the option chosen from a select field.
The javascript contains a lot of other stuff, but only the following is relevant to this question.
$(function (){
$('.source').live("change", function(e) {
var target = $(this).next('.target')[0];
----other stuff----
});
});
I originally had my form set up as follows, and everything worked fine.
<select class="source"></select>
<input class="target"></input>
I've subsequently added some styling, which has required extra divs.
<select class="source"></select>
<div class="level1">
<div class="level2">
<input class="target"></input>
</div>
</div>
Now the javascript function does not work, because the next method only targets siblings and not descendants.
So my question is, what method should I be using to target a specific descendant?
An important fact: this markup is part of a nested form, and is repeated several times on the same page. It is important that the function targets the correct .target field, i.e. immediately subsequent and descendant.
I've tried obvious candidates – .find(), .children() — but these don't seem to work. Would appreciate any ideas or pointers.
Thanks!
Now that in the new markup structure .target input is wrapped in a div with class level1 you can find that div first using next() and then use find() method to get to the .target input.
$(function (){
$('.source').live("change", function(e) {
var target = $(this).next('.level1').find('.target')[0];
----other stuff----
});
});
Note: Even if you don't pass any selector to next() also it will work fine because it only selects the immediate next sibling optionally filtered by the selector which we pass.
In your case this would work:
$(function (){
$('.source').live("change", function(e) {
var target = $(this).next().find('.target')[0];
----other stuff----
});
})
;
It's a descendant of the sibling, so this should do the trick:
var target = $(this).next('.level1').find('.target')[0];
I'm trying to figure out if something like this would be possible. We are given that HTML structure
<a href='#' class='anyLink'>
<!-- here goes some content-->
<div class='childElement'><!-- here goes some content--></div>
</a>
I am not able to use ID's because there are many links and it's not defined how many more are to come. So my question is, do you guys know a way where I can do something like this :
$('a').on("click",function(e){
$(this +"div").val(); // for example.
});
I want to select a children element of that anchor that has been clicked or want to get the value of the children element. I also don't have any ID's of the children elements and I am trying to select things via CSS Selectors as td:nth-child(4).
Could anybody tell me if this is possible ?
try
$('a').on("click",function(e){
$("div",this).text(); // for example.
});
$('a').on("click",function(e){
$(this).children("div").eq(0).html();
});
You are looking for a function called .children().
But you can also try something like this:
$('a').on('click', function( e ) {
$('div', this).val(); // Each div child of this element
$(this).children('div'); // Each div child of this element
});
I'm sure the answer to this is simple, I've just been able to figure it out.
I have a simple click function which applies to any links in a list being clicked. When one is clicked, I want it to remove a class on a div, which is related to one of the links attributes. E.g:
// The link
<li>example1</li>
// The div
<div id="example1" class="selected"></div>
This is the kinda thing that I've tried, but it aint right:
$("ul.switcher a").click(function(e){
e.preventDefault();
$("#" + $(this().val).removeClass("selected");
});
Any help would be much appreciated! If anyone could also tell me the JavaScript equivalent of doing this too that would be a nice bonus!
Well you're close:
$("ul.switcher a").click(function(e){
e.preventDefault();
$("#" + this.title).removeClass("selected");
});
For this sort of thing, the HTML5 "data-" attribute convention can be very handy. You'd change the markup as follows:
<li>example1</li>
Then in your code you can use the jQuery ".data()" method:
$("ul.switcher a").click(function(e){
e.preventDefault();
$("#" + $(this).data('targetId')).removeClass("selected");
});
That technique allows you to avoid "overloading" other attributes, as you've done with "title". (That's not necessarily a bad thing to do, of course, but sometimes you might want the "title" to be something meaningful, since it will after all show up when the mouse is positioned over the element.)
Change
$("#" + $(this().val).removeClass("selected");
to
$("#" + this.title).removeClass("selected");
That works because the title property of the raw DOM object reflects the "title" attribute. Details here in the draft HTML5 specification, and here in the more-established DOM2 HTML specification.
Try this,
Call the following javascript function on your link click (used jquery as well),
function removeClass()
{
if ( $('#example1').hasClass('selected') ) //Will check whether the div has the mentioned class.
{
$('#example1').removeClass('selected'); //This will remove the specified class from the div.
}
else
{
$('#example1').addClass('class1'); //This can be used to add a class to the div.
}
}
Hope this helps...
I googled and googled and I concluded that it's very hard to get answer on my own.
I am trying to use jquery or JavaScript to get a property of clicked element. I can use "this.hash" for example - it returns hash value I presume.
Now I would like to get name of the class of clicked element.
Is it even possible? How? And where would I find this kind of information?
jQuery documentation? - All I can find is methods and plugins, no properties.. if its there - please provide me with link.
JavaScript documentation? - is there even one comprehensive one? again please a link.
DOM documentation? - the one on W3C or where (link appreciated).
And what is this.hash? - DOM JavaScript or jQuery?
In jQuery, if you attach a click event to all <div> tags (for example), you can get it's class like this:
Example: http://jsfiddle.net/wpNST/
$('div').click(function() {
var theClass = this.className; // "this" is the element clicked
alert( theClass );
});
This uses jQuery's .click(fn) method to assign the handler, but access the className property directly from the DOM element that was clicked, which is represented by this.
There are jQuery methods that do this as well, like .attr().
Example: http://jsfiddle.net/wpNST/1/
$('div').click(function() {
var theClass = $(this).attr('class');
alert( theClass );
});
Here I wrapped the DOM element with a jQuery object so that it can use the methods made available by jQuery. The .attr() method here gets the class that was set.
This example will work on every element in the page. I'd recommend using console.log(event) and poking around at what it dumps into your console with Firebug/Developer tools.
jQuery
$(window).click(function(e) {
console.log(e); // then e.srcElement.className has the class
});
Javascript
window.onclick = function(e) {
console.log(e); // then e.srcElement.className has the class
}
Try it out
http://jsfiddle.net/M2Wvp/
Edit
For clarification, you don't have to log console for the e.srcElement.className to have the class, hopefully that doesn't confuse anyone. It's meant to show that within the function, that will have the class name.
$(document).click(function(e){
var clickElement = e.target; // get the dom element clicked.
var elementClassName = e.target.className; // get the classname of the element clicked
});
this supports on clicking anywhere of the page. if the element you clicked doesn't have a class name, it will return null or empty string.
$('#ele').click(function() {
alert($(this).attr('class'));
});
And here are all of the attribute functions.
http://api.jquery.com/category/attributes/
You can use element.className.split(/\s+/); to get you an array of class names, remember elements can have more than one class.
Then you can iterate all of them and find the one you want.
window.onclick = function(e) {
var classList = e.srcElement.className.split(/\s+/);
for (i = 0; i < classList.length; i++) {
if (classList[i] === 'someClass') {
//do something
}
}
}
jQuery does not really help you here but if you must
$(document).click(function(){
var classList =$(this).attr('class').split(/\s+/);
$.each( classList, function(index, item){
if (item==='someClass') {
//do something
}
});
});
There's a way to do this without coding. Just open the console of your browser (f12?) and go to element you want. After that, hover or click the item you want to track.
Every change done on the DOM will be for a few seconds marked (or lightened) as another color on the console. (Watch the screen capture)
On the example, each time I hover a "colorItem", the 'div' parent and the "colorItem" class appears lightened. So in this case the clicked class will be 'swiper-model-watch' or 'swiper-container' (class of the lightened div)