I have a script that places divs according the position of mouse on the body of a page. I have a button which says "Clear" and I want to use it to clear the divs created. How can I achieve that?
The script and source I have written:
HTML
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script src="bhaiya.js"></script>
<button style="z-index: 2000;" class="clear" onclick="clear()">Clear</button>
</body>
</html>
jQuery
$(document).ready(function(){
$(this).mousedown(function(e){
$x = e.pageX;
$y = e.pageY;
$div = "<div class='theDiv' style='width: 250px; height: 150px; background-color:#e7e7e7; position: absolute; top:" + $y + "px; left:" + $x + "px;'>Hey</div>";
$("body").prepend($div);
});
function clear() {
$(".theDiv").remove();
}
})
jsFiddle: http://jsfiddle.net/BpAYz/
Any help would be appreciated :)
You need to either move the function outside the ready handler (making it global), or, better, bind the click with jQuery: $(document). ready(function(){ $(this). mousedown(function(e){ var $x = e.
To remove elements and content, there are mainly two jQuery methods: remove() - Removes the selected element (and its child elements) empty() - Removes the child elements from the selected element.
In jQuery, in order to remove element and content you can use anyone of the following two jQuery methods: Methods: remove() – It is used to remove the selected element (and its child elements). empty() – It is used to removes the child elements from the selected element.
For removing the element using jQuery, we can use element name, element id, element class etc. We can remove a single or multiple elements using jQuery remove() function. For this example, first, we need a JS file for accessing the remove() function.
Inline html attribute event handlers can only call global functions. Your clear()
function is not global because it is defined inside your document ready handler, so your onclick="clear()"
can't find it. You need to either move the function outside the ready handler (making it global), or, better, bind the click with jQuery:
$(document).ready(function(){
$(this).mousedown(function(e){
var $x = e.pageX;
var $y = e.pageY;
var $div = "<div class='theDiv' style='width: 250px; height: 150px; background-color:#e7e7e7; position: absolute; top:" + $y + "px; left:" + $x + "px;'>Hey</div>";
$("body").prepend($div);
});
$(".clear").click(function () {
$(".theDiv").remove();
});
});
Note also that I've added var
in front of the variables in your mousedown handler: without var
they become global variables, which just makes your code more error prone and hard to debug. (Unless you have a good reason why they should be globals?)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With