I have a fairly complex situation (to me at least):
I have a click function that was used to show an overlay. Inside the click function, the element in question is determined dynamically:
$('a.overlay-show').click(function() {
var id = $(this).attr('id');
var el_id = '#project-details-overlay-' + id;
Now what I'd like to do is something like:
$(el_id).detach();
But I am seeing that this doesn't work because I am passing in an element not a selector. So how would one do this?
What I need to do is grab that element and re-attach it somewhere else. I have tried to just deal with the element's contents using .html() and so forth but because the content, at times contains javascript elements such as slideshows, this doesn't seem to work out too well...
Any suggestions?
should work this way:
$('a.overlay-show').click(function() {
var id = $(this).attr('id');
var el_id = $('#project-details-overlay-' + id);
el_id.detach();
});
i'm not familiar with detach.. if you're trying to move it somewhere else:
<div id="somewhereElse"></div>
then you would write:
el_id.appendTo('#somewhereElse');
if you want to keep it where it is AND copy it somewhere else:
el_id.clone().appendTo('#somewhereElse');
lastly, if you're not using el_id anywhere else beyond this one line of code, you don't even need the extra variable... just condense the var statement and the append statement into one:
$('#project-details-overlay-' + id).appendTo('#somewhereElse');
Thanks #erikruina - appendTo() works much better. I ended up fixing it with
$('a.overlay-show').click(function() {
var id = $(this).attr('id');
var el_id = $('#project-details-overlay-' + id);
$(el_id).appendTo('#selected-project');
});
I suspect that the issue is that with detach(); you also need to deal with all the child elements, whereas appendTo() just works.
Related
I'm trying to add a search link to an online form with a userscript using jQuery. I don't work too much in firefox and I feel like things that would normally work in chrome don't in ff 9/10 times for me. But anyway... this needs to be with ff.
I'm taking the text from a <p> element and creating a search url out of it (or trying to). Right now this is the function I'm trying that should be doing it... but it's doing nothing, not even any errors in console
$(function() {
var companyName = $('p')[7]; // Element that contains the name text
var companyText = companyName.text(); // Retrieve the text from element
var mixRankUrl = $("<a></a>").innerHTML("Search Mixrank"); // Create an <a> element
mixRankUrl.href = 'https://mixrank.com/appstore/sdks?search=' + companyText; // Define the href of the a element
var sdkPara = $('label.control-label')[10]; // Where I want it to go
sdkPara.append(mixRankUrl); // Append the element
});
Also, whoever wrote the html uses hardly any ids, and most classes are assigned to 10 or more elements... so unless there's a better way, I'm sort of stuck using node selectors (which stay the same form to form).
The problem is that you try to use jQuery method on DOM element. Don't understand why you don't have any errors with your code.
For exemple : $('p')[7] return a DOM element while $('p').eq(7) return a JQuery object. So you can't use a jQuery method like text() on your DOM element. You need to deal with jQuery object.
For the same reason, you had a problem with the declaration of your label object and with the modification of the href attribute of your link.
Try like this :
$(function() {
var companyName = $('p').eq(7); // Element that contains the name text
var companyText = companyName.text(); // Retrieve the text from element
var sdkPara = $('label.control-label').eq(10); // Where I want it to go
var mixRankUrl = $('<a>',{
text: 'Search Mixrank',
href: 'https://mixrank.com/appstore/sdks?search=' + companyText
}).appendTo(sdkPara); // Append the element
});
I tried to set it up so that it checks to see if it has another variable, and if it doesn't, add it.
var item = "<li>Testing</li>";
var hasItem = $(".target-class").has(item).length;
if(hasItem == 0) {$(".target-class").append(item)}
This doesn't work and it keeps appending item forever.
.has expects a selector, not HTML:
var item = '<li class="testing">Testing</li>';
var hasItem = $(".target-class").has('li.testing').length;
Please read the documentation.
So if your HTML were:
<div class="target-class"></div>
Then the below while loop would add the div element once and then stop executing:
var item = "<li class='testing'>Testing</li>";
var targetEl = $(".target-class");
while (!targetEl.has("li.testing").length) {targetEl.append(item);}
http://jsfiddle.net/cssimsek/qdpFJ/
I actually had
var hasItem = $(".target-class").has(item).length;
messed up. It wasn't selecting what I thought it was selecting. As a tip for anyone new to jQuery, add .remove() to the end of your selector. When you are removing exactly what you want to select then you know you have it right. Just remove .remove() and you are good to go.
Along with fixing .has(item), it now works.
I have a page that can have one of three possible elements. I would like to assign whatever element exists to a var and then check if the var is clicked.
I tried using the add(), but it has confused me:
var testingVar = $('#element-one').find('.object').add('#element-two').find('.object').add('#element-three').find('.object');
$(testingVar ).click(function() {
alert('works');
});
It seems to me that the add() overwrites the previous add()? if I am on a page that has #element-three, it works, if on a page with element-one or element-two, it doesn't. If I change the var to
var testingVar = $('#element-one').find('.object');
Then a page with element-one works.
Can someone help me understand how to use the add() properly in this case?
Thanks
I think what you're looking for is this:
$('#element-one .object').add('#element-two .object').add('#element-three .object');
.find() returns a new jquery object.
However, I think this would be easier in this case:
$('#element-one .object, #element-two .object, #element-three .object');
Or even easier, if you can change markup, is to give each element you're currently selecting by id a common class, and do this:
$('.common-class .object')
I've got a modal window. What I want to happen is to remove certain elements from the page when the modal opens and add them back in right where they were after the modal closes. I don't want to do display:none, because that only hides them, I need them to actually be removed from the page. So I have a bit of jQuery to remove and add them back in after a timer just for testing...
UPDATED: With these additions to the code, it now grabs the element before, then adds it back in after that same element. The issue is, what if that element was also removed? Then it won't add back in! Also, won't javascript event handlers be lost in this? I'm developign a plugin, so it should interfere with the site as little as possibl,e but 3d elements have a bug in them with Safari that is impossible to get around.
Any ideas on how I could temporarily remove 3d elements without interfering with people's site too much?
$3delements = $('*').filter(function(){return $(this).css('-webkit-transform-style') == 'preserve-3d'});
$3delementsposition = $3delements.prev()
//On modal open
$3delements.remove();
//On modal close
$3delementsposition.after($3delements);
The problem is that this requires I specify a certain place in the DOM for them to come back in. I'd like the elements to come back in where they were. How can I make sure the elements don't change/move/lost information on the .remove to the .append.
Use .detach() and .append() to remove and reattach elements, it will maintain all your events and data.
If you add elements back in the reverse order that you removed them, they should all fall back in place
untested code
var elems3d = $(...);
var elemsRemoved = [];
// removing
elems3d.each(function(i,o) {
var elem = $(o);
elemsRemoved.push({
loc: elem.prev(),
obj: elem.detach()
});
});
// adding back
while (elemsRemoved.length) {
var elem = elemsRemoved.pop();
elem.loc.after(elem.obj);
}
Instead of removing the elements, replace them with placeholder elements (using replaceWith) then replace the placeholders with the original content when needed. Something like the following:
$3delements = $('*').filter(function(){return $(this).css('-webkit-transform-style') == 'preserve-3d'});
var originals = [];
$3delements.each(function() {
// Clone original, keeping event handlers and any children elements
originals.push($(this).clone(true));
// Create placeholder for original content
$(this).replaceWith('<div id="original_' + originals.length + '"></div>');
});
///
/// Do something asynchronous
///
// Replace placeholders with original content
for (var i in originals) {
$('#original_' + (i + 1)).replaceWith(originals[i]);
}
See clone and replaceWith in the jQuery docs for more info.
I have created the fiddle. Let me know if this fulfills your requirement.
http://jsfiddle.net/mNsfL/12/
I use html's data- attribute on a list of menu links in order to tie the links to the div ids of sections of content I want to open when the links are clicked. So if I have a hidden div called "#section1" - the link that would open that link is .
Currently, in order to find the div that matches this link, I use jquery .each() to loop through all the possible elements, but it seems like there should be a better way.
Does anybody know how I could streamline this code and find the matching element without having to run the code in a loop?
Here's my code:
$('a.hidden_link').click(function(){
section_ident = $(this).attr('data-ident');
$('.hidden_section').each(function(index) {
if ($(this).attr('data-ident') == section_ident){
section_ref = $(this);
section_ref.show();
}
});
});
This should work.
$('a.hidden_link').click(function(){
$(".hidden_section[data-ident='"+$(this).attr('data-ident')+"']").show();
});
Jsfiddle, http://jsfiddle.net/playerace/H7jwb/
$('.hidden_section[data-ident="' + section_ident + '"]').show();
all together:
$('a.hidden_link').click(function(){
var section_ident = $(this).attr('data-ident');
$('.hidden_section[data-ident="' + section_ident + '"]').show();
});
This sounds like a job for jQuery.filter()!
$('a.hidden_link').click(function(){
var section_ident = $(this).data('ident');
$('.hidden_section').filter(function() {
return this.attributes["data-ident"] == section_ident;
}).show();
});