new to StackOverflow and relatively new to JavaScript/jQuery. I've been trying to develop a website that contains a vector map (using the Raphael plugin), and when a particular area of the map is clicked, I want it to open a Lightbox using the Colorbox plugin. I have the Raphael and Colorbox plugins working individually (I've got the hover function working for Raphael, and I've got the Colorbox to work when a normal link is clicked). However, I'm not sure how to get the Colorbox to work when it is a Raphael element that is clicked.
This is because I think I need to add the "inline" class to the Raphael element, however my .click function can only get a url (I can't add a class).
Apologies if this question doesn't make much sense, I've been going round in circles for hours now.
Current .click function. locs is an array of the Raphael objects in a separate document. locarr is an array containing these objects for a for-loop. id and url are elements of the Raphael object.
.click(function(){
location.href = locs[locarr[this.id]].url
})
The Colorbox works with a normal link, like below. But I can't figure out a way to add the class to my .click function. I've tried various versions of .addClass and similar with no success.
LINK
I think my problem is because the Raphael objects do not exist in the HTML (the url is taken straight from the JavaScript document.
Sorry again if this doesn't make sense. Thanks.
Not going to pretend to try and understand full well what you want, so I am going off the current title. If thats the case and you want to add a class to an element for styling purposes of one sort or another and you want it to do this when the link is clicked on you can try..
$('.inline').click(function(e)
{
e.preventDefault();//stops the mouse click from triggering a normal click event
$(this).addClass('className');//adds a defined class from your stylesheet
//$(this).css({"color":"#FF0"});//changes the style properties without a class
});
Since your saying in the comments your JS is generating the link. You can try..
$('body').delegate('click', '.inline', function(e)
{
e.preventDefault();//stops the mouse click from triggering a normal click event
$(this).addClass('className');//adds a defined class from your stylesheet
//$(this).css({"color":"#FF0"});//changes the style properties without a class
});
or you can try
$('.inline').live('click', function(e)
{
e.preventDefault();//stops the mouse click from triggering a normal click event
$(this).addClass('className');//adds a defined class from your stylesheet
//$(this).css({"color":"#FF0"});//changes the style properties without a class
});
Related
I am still a bit new to JS & JQuery, so please excuse what may be a simple and stupid question.
Background:
I have a div on my page that holds several divs (#idle-variable). On click of the top level div, it basically shows the other divs (#addvariable). Nothing more than display: none; and .show(). Easy. On another action within that div (change of drop down), I essentially want to inject/insert that top level div (#idle-variable) underneath the first instance.
Issue:
Essentially, the .click function is not working on my newly inserted div. This may be because the two div's share the same ID, BUT I have a sneaky suspicion that it's not recognized in the DOM. A friend of mine said something about I have to "re-run" my jquery in order for it to be readable in the DOM.
Question:
How can i make this work properly? I want to be able to add a dynamic number of these idle-variables to the page and I need to make sure my .click function works for all added DIVS.
$(function(){
$('#idle-variable').click(function(event) {
$("#addvariable").show(400);
});
});
//create variable in db & show value entry
$("#variabletype").change(function() {
$("#varholder").css("display", "inline-block");
$.ajax({
type: "POST",
url: "/myphpfile.php",
data: {"variabletype": $("#variabletype").val()},
success: function(){
$( "#idle-variable" ).after("<div id="#idle-variable>content</div>");
}
});
});
Well to make the code work it would need to use on and ids are only supposed to be on one element. If it can be on the page multiple times you need to use classes.
$(document).on("click,'#idle-variable', function(event) {
$("#addvariable").show(400);
});
you should be using classes
$(document).on("click,'.idle-variable', function(event) {
//$("#addvariable").show(400); //not sure how this relates to the clicked element.
$(this).find(".addvariable").show(400); //if it is a child
});
You also have a typo in your code with quotes.
The ID based selector will be applied to the first element only.
See the example here http://jsfiddle.net/9GN2P/2/
If you are looking to bind same event handler to multiple elements, definitely go with the class based approach, instead of ID based approach.
And, you are expecting event handler to work with dynamically created elements as well. If you are using older versions of jquery, use the live method like
$('yourselector').live('click',function(){
});
Since live is deprecated and if you are in a new version, use the 'on' method
$('containerselector').on('click','yourselector',function(){
});
Editing to answer your comment:
To create dynamic element and append to DOM, you can follow the bellow pattern. Here, I will create a DIV with id "newID", class "newClass", content "NEW DIV!!" and a click event handler for it. And it will be pushed into another div with id 'containerID'
$('<div />',{
id:'newID',
'class':'newClass',
text:'NEW DIV!!',
click:function(){alert('hi');}
})
.appendTo('div#containerID');
This is just a demo.
I'm trying to dynamically add some CSS classes to some elements that I don't have control over the creation of. I know that the divs I'm looking for will be added like this: mydiv.appendChild(resdiv). However, I cannot add code at that point at which they're created. I know that every instance of this div that is dynamically added will have a specific CSS class (let's call it output-class). I could theoretically add CSS rules to that specific class, but I'd rather not - it would result in the duplication of a lot of styles.
What I want to do is fire an event as soon as a div with the output-class class is added to the page. I'm trying to add some more CSS classes on the fly. Here's what I have so far:
jQuery('body').on('DOMNodeInserted', ".output-class", function(event) {
var el = $(this);
el.addClass('my new class');
// do some more manipulation of the new div (el).
});
However, as far as I can tell, this callback is never called. What am I doing wrong?
There are several related question involving DOM Insertion including this one which contains the following code:
document.addEventListener("DOMNodeInserted", function(event) {
alert($(event.target).parent()[0].tagName);
});
When a draggable attribute is enabled on a parent element(<li>) I cant make contenteditable work on its child element (<a>).
The focus goes on to child element (<a>),but I cant edit it at all.
Please check this sample
http://jsfiddle.net/pavank/4rdpV/11/
EDIT: I can edit content when I disable draggable on <li>
I came across the same problem today, and found a solution [using jQuery]
$('body').delegate('[contenteditable=true]','focus',function(){
$(this).parents('[draggable=true]')
.attr('data-draggableDisabled',1)
.removeAttr('draggable');
$(this).blur(function(){
$(this).parents('[data-draggableDisabled="1"]')
.attr('draggable','true')
.removeAttr('data-draggableDisabled');
});
});
$('body') can be replaced by anything more specific.
If new contenteditable elements are not added in the runtime, one can use bind instead of delegate.
It makes sense that the draggable and contenteditable properties would collide. contenteditable elements, like any text field, will focus on mousedown (not click). draggable elements operate based on mousemove, but so does selecting text in a contenteditable element, so how would the browser determine whether you are trying to drag the element or select text? Since the properties can't coexist on the same element, it appears that you need a javascript solution.
Try adding these two attributes to your anchor tag:
onfocus="this.parentNode.draggable = false;"
onblur="this.parentNode.draggable = true;"
That works for me if I add it to the <a> tags in your jsFiddle. You could also use jQuery if it's more complicated than getting the parentNode.
Note: This is a workaround since I believe the inability for these two functionalities to work together resides in the HTML spec itself (i.e. the not working together thing is intentional since the browser can't determine whether you want to focus or drag on the mousedown event)
I noticed you explicitly set 'no libraries', so I will provide a raw javascript/HTML5 answer
http://jsfiddle.net/4rdpV/26/
This was my crack at it.
First of all, it might be better to include the data in one single localStorage item, rather than scatter it.
storage={
'1.text':'test 1',
'2.text':'test 2'
}
if(localStorage['test']){
storage=JSON.parse(localStorage['test'])
}
this creates that ability, using JSON to convert between object and string. Objects can indeed be nested
I also added (edit) links next to the items, when clicked, these links will transform the items into input elements, so you can edit the text. After hitting enter, it transforms it back and saves the data. At the same time, the list items remain draggable.
After saving, hit F12 in chrome, find the console, and look in the localStorage object, you will see all the data was saved in localStorage['test'] as an Object using JSON.stringify()
I tried my best to design this to be scaleable, and I think I succeeded well enough; you just need to replace the HTML with a container and use a javascript for loop to write out several items, using the iterator of your choice to fill the parameter for edit(). For example:
Say you changed storage to hold "paradigms" of lists, and you have one called "shopping list". And say the storage object looks something like this:
{
"shopping list":{
1:"Milk",
2:"Eggs",
3:"Bread"
}
}
This could render that list out:
for(i in storage['shopping list']){
_item = storage['shopping list'][i];
container.innerHTML+='<li draggable=true><a id="item'+i+'">'+_item+'</a> (edit)</li>'
}
Of course, if you were to edit the structure of the storage object, you would need to edit the functions as well.
The output would look something like this:
Milk (edit)
Eggs (edit)
Bread (edit)
Don't worry about the input elements if that worries you; CSS can easily fix it to look like it didn't just change.
If you don't want the (edit) links to be visible, for example, you can do this in CSS:
a[href="#"]{
display:none;
}
li[draggable="true"]:hover a[href="#"]{
display:inline;
}
Now the edit links will only appear when you hover the mouse over the list item, like this version:
http://jsfiddle.net/4rdpV/27/
I hope this answer helped.
Using html5sortable and newer JQuery events (delegate is deprecated, answer 3 years after initial question), bug still affects Chrome 37. Contenteditable spans and html5sortable seem to play nice in other browsers. I know this is only partially relevant, just keeping documentation on changes I've noticed.
$(document).on('focus', 'li span[contenteditable]', function() {
$(this).parent().parent().sortable('destroy'); // removes sortable from the whole parent UL
});
$(document).on('blur', 'li span[contenteditable]', function() {
$(this).parent().parent().sortable({ connectWith: '.sortable' }); // re-adds sortable to the parent UL
});
I have a form that I am trying to alter with jQuery. Basically, my form has two elements and I need to change the value of the first option in each of them. However, there is an "add more" option that uses AJAX to dynamically generate another element that also needs changed. This add more button can be clicked an unlimited amount of times.
Right now I have this:
$(document).ready(function(){
$("#myname-0-field option:first").val("None");
$("#myname-1-field option:first").val("None");
});
This works fine, but once the "add more" button is clicked, I have more elements called "#myname-2-field", "#myname-3-field", "#myname-4-field" etc. These obviously aren't affected by adding another line into my jQuery as the document has already loaded when they are added.
So the real question is, can someone point me in the right direction of writing a function that can react when the new element is added and change it. If possible, I'm also looking for the function to be aware and look for "#myname-X-field option:first" for tidyness.
use live() function
Then using each function set value
From the jQuery API look live function
Maybe you could add class to your element, so that finding particular element would be easier and it would not add event to other similar elements.
In the example I have a Li with class
$('li.myClass').live('click', function() {
$(this).val(); // this is the getter for clicked value
$(this).val("some_value_here"); // this is the setter for clicked value
});
Now you can add more elements (that has myClass class) and it will have a click event.
Btw. if you know that all elements are inside some container (div for example) then you can write more efficient jQuery using delegate.
$('#container_id').delegate('li.myClass', 'click', function () {
});
This is more efficient because it looks your new elements only under "containter" not from the whole DOM structure.
Say i have 10 small images that i want to use as tooltips.
Im assinging them all the same class, '.helper'
Im selecting helper, then calling
mouseenter(function() { $(".helper").stop(false,true).fadeIn(); })
I then want a div to popup, containing some text. This works fine if there's only one tooltip on the page, but as soon as there is more than one, whenever i hover over one, they all appear at the same time.
Have i got something fundamentally wrong?
Comments appreciated.
Thx
Use this as the selector inside instead of the .helper selector again:
$('.helper').mouseenter(function() {
// "this" now refers to the image that is being hovered...
$(this).stop(false, true).fadeIn();
});
If you're wondering what the problem was, it was that when you called
$(".helper")
within your function, you were getting all the elements with class helper, in stead of just the single element you wanted.