I'm reading the jquery manual regarding the .after() function:
$('.container').after($('h2'));
and it says
"If an element selected this way is inserted elsewhere, it will be
moved rather than cloned"
So if I have multiple
<div class='before' onclick='afterfunction();'><div>,
and I would want to place <div class='after'></div> after whichever div is clicked (have it move, not clone) would I do something like this?
var afterdiv = "<div class='after'></div>";
function afterfunction() {
$(this).after(afterdiv);
}
Thanks for all your help!
Like you said:
An element in the DOM can also be selected and inserted after another element:
$('.container').after($('h2'));
If an element selected this way is inserted elsewhere,
it will be moved rather than cloned:
But you missed the bold part.
$('.before').click(function() {
afterfunction(this);
});
// this will not work cause you'll append a string to your DOM
// var afterdiv = "<div class='after'>ola</div>";
// and will repeatedly be appended after each action.
// instead define your element by wrapping it into a $( )
var afterdiv = $("<div class='after'>ola</div>");
// now 'afterdiv' variable is binded to that element only once inside the DOM
function afterfunction(elem) {
$(elem).after(afterdiv);
}
And you don't need to .remove() it (like wrongly suggested in an answer here.)
demo jsFiddle
Make .before div like this:
<div class='before'><div/>
Then try,
$('.before').on('click', function() {
afterfunction(this);
});
function afterfunction(el) {
var afterdiv = "<div class='after'></div>";
$('.after').remove(); // remove previous `.after`
$(el).after(afterdiv); // add newly after the clicked div
}
DEMO
Related
I am basically trying to print the value of a button in the div with list class if the button is selected. Also remove the same value wwhen it is deselected. I am able to print the value successfully but not able to remove it. Could somebody please help me out with it.
var buttonSelect = $(".btn").click(function() {
if ($(this).hasClass('active')){
$(".list").append(this.value + " ")
}
else {
$(".list").remove(this.value)
}
});
You should rather append the content along with html element like span:
$(".btn").click(function() {
if ($(this).hasClass('active')){
$(".list").append('<span class="newval_'+this.value+'">'+this.value + "</span>");
}else{
$(".list").find('.newval_'+this.value).remove();
}});
The parameters from .remove() is a selector, just having a value in there that contains the content of the element you want to remove will not work. For example if I had this:
<li class="list">test</li>
Doing $(".list").remove("test") will not remove it. You will probably want to use the :contains selector (since you may have the value with spaces at the end). So in the example above doing $(".list").remove(":contains('test')") will remove the element. You can do the same thing in your case:
$(".list").remove(":contains('"+this.value+"')");
If you want to remove the element itself along with everything in it, just use jQuery’s remove() method.
$(document).ready(function() {
$("button").click(function() {
$("div").remove(); //remove Div element
});
});
You can see an example here: How to Remove Elements from DOM in jQuery
I have a div that looks like this:
<td id="monday">
<p class="outter">whatever here</p>
<p class="hidden" style="display:none">Some content I want to get</p>
</td>
Now the problem is - the td id will change (this is just one of many).
So what I'm trying to do, is when a user clicks on the .outter (it'll always be called outter), I want to find the td id, in order to then get access to the p class (which will always be 'hidden').
So I've tried this (document.body is to get round a dynamic loading problem I had):
$(document.body).on('click', '.outter', function() {
var info = $(this).parent("td").$(".hidden").text();
$("#rightBox").css("width", "200px");
$("#rightBox").css("background", "#f0f0f0");
$("#rightBox").empty();
$("#rightBox").append(info);
});
The issue I am having is in the very first line, getting the variable.
I want to say this particular .outter class, find it's parent, then find the hidden class within it. Then get the text within that hidden class. Then take that variable and dump it into #rightBox;
Can anybody help?
The line var info = $(this).parent("td").$(".hidden").text(); throws an error, you should use find or children method, as the target element is a next direct sibling of the clicked element, you can use next method, you don't need the ID of the parent element.
$(document.body).on('click', '.outter', function() {
// var info = $(this).closest('td').find('.hidden').text();
var info = $(this).next('.hidden').text();
$("#rightBox").css({"width": "200px", "background": "#f0f0f0"})
.html(info);
});
Note that you can also create a class and use addClass method instead of css method, this makes your code a little cleaner.
You can do like this:
$(document.body).on('click', '.outter', function() {
var info = $(this).next().text();
$("#rightBox").css("width", "200px");
$("#rightBox").css("background", "#f0f0f0");
$("#rightBox").empty();
$("#rightBox").append(info);
});
Demo: http://jsfiddle.net/eMzcx/
I am trying to add a click event to a bunch of div elements that I created by appending them and I am having some trouble.
I have a bunch of div elements the with the ids a0 ---> an. I am trying to create a for loop after the divs are created to assign them click events. The issue is the way I am doing it when the click event happens I do not have any way to track which div fired the event. The code bellow might make that more clear. So the issue I am having is that #a + i always returns the last div, and I want it to return the div number that was clicked.
$(document).ready(function () {
traverse(oo);
for (i = 0; i <= groupNum; i += 1) {
$("#a" + i).click(function () {
console.log("#a" + i + "clicked");
});
}
});
I thought about returning a closeur, but that seems I would make it even more complicated. Does anybody have any advice on how to do this the best?
Thanks in advance.
I'm not sure what you are trying to do but if you just want to assign a click event to a bunch of elements then use the correct selector (note the use of $(this) to get the clicked element):
$("div").click(function(){
var clickedDiv = $(this);
var id = clickedDiv.attr("id");
});
If you don't want ALL div elements, then you could add a class to them and use a different selector:
$(".MyDivClass").click(function(){...
or without the class, a 'starts with' on the id (the following with get all div elements where the id attribute starts with "a"):
$("div[id^='a']").click(function(){...
If you are dynamically adding divs with other javascript and you want them to automatically have the click events, use the on function...
$(document).on("click", ".MyDivClass", function(){...
The variable i will, as you noticed, will contains the value set on the last iteration. Change
console.log("#a" + i + "clicked");
by
console.log(this.id + " clicked");
Within the event handler, this is the target DOM element for the event.
You can do it in this way:
$('[id^="a"]').click(function () {
console.log(this.id+" clicked");
});
You may assign a click event to a class instead of to specific ID's and use conditional statements within the click function to do different things base on ID.
$(documnet).ready(function(){
$('.clickclass').click(function(){
/* conditional code here */
});
});
i want to read all links in ".vm-video-title"-divs and post them each in the same div. So i made this script:
$('.vm-video-title').each(function(i) {//all divs
$(this).html($(this).html()+$("div.vm-video-title>a").text());//add to div the link
});
but i have the problem that it reads ALL the links of all divs and put them in one div.
example:
<div class="vm-video-title">Text1</div>
<div class="vm-video-title">Text2</div>
<div class="vm-video-title">Text3</div>
output:
Text1Text1Text2Text3
Text2Text1Text2Text3
Text3Text1Text2Text3
wanted output:
Text1Text1
Text2Text2
Text3Text3
You can select the <a> elements directly, and use the after()[docs] method to append the content of each after each one respectively.
$("div.vm-video-title > a").after(function() { return $(this).text(); });
This doesn't do a "destroy then recreate" of the existing elements like the html()[docs] method will.
Working example: http://jsfiddle.net/CCr9C/
This should do the job for you,
you need to find the div inside current element in the loop (el).
$('.vm-video-title').each(function(i, el) {
el = $(el);
el.html(el.html()+el.find("a").text());
});
in your code you are adding text() of all matching "a" tags in your divs (i.e. Text1Text2Text3)
You were almost there. Instead of : $("div.vm-video-title").text(), which gives you text inside any div with class vm-video-title, you need to find a tag inside current div and get text from it. We pass this as context for selecting a inside current div jQuery( selector, [context] )
$('.vm-video-title').each(function(i) {//all divs
$(this).html($(this).html()+$("a", this).text());
});
Update: Everyone that contributed, it's well appreciated, you all are very kind and generous and all of you deserve my dear respect. Cheers.
Note: I'm making a simple jQuery tooltip plugin, the tooltip will fire on mouseover. The mouseover will create an instance of the div tool-tip that will be specific to each anchor that launched the div tool-tip. So each anchor with the class .c_tool will have its own created div that will erase after mouseout. Anyway all those details are irrelevant. What is important is how to create a div with .append() or .add() on and then find a way to call it and apply actions to that div without setting an identifier (id), class, or any means to identify it.
I know theres a way you could find the div by counting, so if you gave every created div the same class and then counted them to find that one, however I don't know if this is the most efficient method that is why I'm asking for help.
I'm not going to post the whole plugin script thats unnecessary, so I'll paste a simplified version.
hover me
hover me
$(document).ready(function() {
obj = $('a.c_tool');
obj.mouseover(function() {
/// append div to body it will be specific to each item with class c_tool, however I don't want to set an ID, or CLASS to the appended div
}).mouseout(function() {
/// remove added div without setting ID or class to it.
});
});
Working example:
http://jsfiddle.net/xzL6F/
$(document).ready(function() {
var tooltip;
obj = $('a.c_tool');
obj.mouseover(function() {
var element = $('<div>', {
html: "I'm a tooltip"
});
tooltip = element.appendTo($("body"));
/// append div to body it will be specific to each item with class c_tool, however I don't want to set an ID, or CLASS to the appended div
}).mouseout(function() {
tooltip.remove();
/// remove added div without setting ID or class to it.
});
});
To create a new DOM node you can use the jQuery constructor, like
$(document).ready(function() {
obj = $('a.c_tool');
obj.mouseover(function() {
if(!$.data(this, 'ref')) {
$.data(this, 'ref', $ref = $('<div>', {
html: 'Hello World!'
}).appendTo(document.body));
}
}).mouseout(function() {
$.data(this, 'ref').remove();
});
});
.appendTo() returns the DOM node of invocation (in this case, the newly created DIV) as jQuery object. That way you can store the reference in a variable for instance and access it later.
Referring your comment:
To remove all stored references, you should do this:
$('a.c_tool').each(function(index, node) {
$.removeData(node, 'ref');
});
you can use $.append(
);
http://api.jquery.com/append/
and to find the DOM created dynamically u can use
$("#dynamicallyCreatedDOMid").live("yourCustomTrigger",function(){
});
http://api.jquery.com/live/