Published on: 11/15/13 5:16 PM
Category:Uncategorized Tags: jqueryMove Html elements with jquery is one of the common task that programmer has to do in UI. We can have many ways to do this task. Its depends on the requirement
ways I am going to discus are as follows
1) we can move with changing the css by jquery
here I have used a flag and set first to 0 and then if user clicked on the button then change the position of button and flag has been changed and then set to 1
then next if user click to button , then flag is already 1 then move the button to its original position again
HTML
[sourcecode language=”csharp”]
<!– move with changin the css —————
———————————–>
<div id="panel1">
<input type="button" value="first Name" id="btn1" />
<br>
<input type="button" value="Last name" id="btn2" />
<br>
<input type="button" value="contact" id="btn3" />
</div>
[/sourcecode]
jquery function
[sourcecode language=”csharp”]
var flag = 0 ;
$("input").click(function () {
if( flag ==1 )
{
$("input").click(function () {
$(this).css("margin-left","0px");});
flag=0;
}
else if( flag == 0)
{
$("input").click(function () {
$(this).css("margin-left","120px");});
flag = 1 ;
}
});
[/sourcecode]
for more , visit Demo
<strong>2) move elements with changing the div’s id </strong>
here I will change the position of the button. Means Initialy i will take the element in one div and then onclick of that button that button will move to the other div
HTML
[sourcecode language=”csharp”]
<!————————————————-
move element with changin div id
————————————————–>
<div id="panel1">
<input type="button" value="add" id="btn1" />
<br>
<input type="button" value="add" id="btn2" />
<br>
<input type="button" value="add" id="btn3" />
</div>
<div id="panel2" style="background-color:gray"></div>
[/sourcecode]
JQuery function
[sourcecode language=”csharp”]
$(document).ready(function(){
$("input[value=’add’]").click(function () {
$(this).appendTo("#panel2");
$(this).val("remove");
// remove();
$("input[value=’remove’]").click(function () {
$(this).appendTo("#panel1");
$(this).val("add");
});
});
});
[/sourcecode]
for more,visit Demo
3) Change class of the element with toggleClass function of the JQuery
this is little bit tricky , here what I will do is , onclick of the element I will toggle the class and change the property of the class ie change the position of the class
HTML
[sourcecode language=”csharp”]</span>
<!– chage the position of the button and name with classToggle –>
<div id="panel1" class="p1">
<input type="button" value="add" id="btn1" />
<br>
<input type="button" value="add" id="btn2" />
<br>
<input type="button" value="add" id="btn3" />
</div>
<div class="p2"></div>
[/sourcecode]
JQuery Function
[sourcecode language=”csharp”]
$("input").click(function () {
$(this).toggleClass("p2");
$(this).css("right", "20px");
if ($(this).val() == "add") {
$(this).val("Remove");
} else {
$(this).val("add");
}
});
[/sourcecode]
for more , Visit Demo