Jquery move div. Another freelance blog


Another chapter from the book “jQuery in Action” (by Bear Bibeault and Yehuda Katz). First of all, I apologize to the readers for such a long gap between the publications of chapters. But I did it anyway, which, of course, I’m glad about. I hope that you too will not remain indifferent. So, let's sell.

Chapter 3. Bringing the page to life with jQuery.3.1. Manipulating properties and attributes of objects.3.1.1. Manipulating object properties. The easiest way to check or change the elements of the set we have selected is with the each() command:

$('img').each(function(n)(
this.alt=’This is image[’+n+’] with id equal to ‘+this.id;
});

This expression will apply the specified function to each element on the page, the alt attribute will be changed using serial number element and its id.

3.1.2, 3.1.3 Getting and changing attribute values. As we'll see later, many methods in jQuery are used for both reading and writing, depending on the attributes and the number of attributes passed to the method.

Thus, the attr() method can be used both to get the values ​​of attributes and to set them. If the method is passed only the name of the attribute, it will return its value, for example:

$(“#myImage”).attr(“alt”)

This is how we get the alt for the element with id #myImage.

$(“#myImage”).attr(“alt”,”My picture”)

As you probably already guessed, we will set the alt “My picture” to the same element.

It is worth noting that instead of a new attribute value, you can pass a function to this method. Example:

$(‘*’).attr(‘title’,function(index) (
return ‘I am element ’+index+’ and my name is ‘ +
(this.id ? this.id: 'unset');
});

This function, which is still complicated for us, runs through all the elements of the set on the page, changing title attribute according to the element index and its id.

Moreover, the attr() method allows you to change multiple attributes at the same time:

$(‘input’).attr((value: ‘’, title: ‘Please enter a value’));

This way we can clear all input values ​​and set their title to “Please enter a value”.

3.1.4 Removing attributes. In order to remove an attribute from a DOM element, jQuery has a special removeAttr() method. For example:

$('img').removeAttr('alt');

This will remove the alt attribute from all selected img elements.

3.2 Working with element styles. 3.2.1 Adding and removing class names. Defining a class is done very simply by using the addClass() method, which assigns the given class name to all elements in the set. For example:

$('img').addClass('noBorder');

Removing a class is done with the removeClass() command:

$('img'). removeClass('noBorder');

The next method is quite interesting: toggleClass() assigns a class to an element in the set if this class has not been defined for it, and, conversely, removes the class from an element in the set if the class has been assigned.

It can be very useful to use this method in tables where, for example, we need to change the shaded rows to white, and the white rows to shaded. This is done like this:

$('tr').toggleClass('stripped');

Where striped was the class name for the striped line.

3.2.2 Getting and installing styles. Working directly with styles gives us great opportunities.

The css() method works similarly to the attr() method, allowing us to set custom CSS properties for an element by passing a name-value pair to a method, or even change multiple properties by passing new values ​​for them in the object.

Moreover, the method also handles functions passed to it as a property value just fine. For example, let's increase the width of the elements in the set by 20 pixels:

$(‘div.expandable’).css(‘width’,function())(
return $(this).width() + 20 + “px”;
});

The following example shows the possibility of passing a group of parameters as objects to a method:

$('div.example').css((width: '100px', height: '200px'));

And finally css method() allows you to get the value of the property passed to the method. For example, you can find out the width of an element like this:

$('div.examle').css('width');

For frequently used properties in jQuery there are special teams. So, we can find out or change the height and width of objects using special methods height() and width(). Accordingly, if we pass a value to a method, we set this value according to the method that received it, and if we simply call the method, we will receive the value we need (in this case, the passed value will be set in pixels), that is:

$('div.example').width(500)

Sets the block width to 500 pixels. By the way, this is the same as

$(‘div.example’).css(“width”,”500px”)

Now you can find out the width of the block like this:

$('div.example').width()

3.2.3 A little more useful commands for working with styles. Sometimes it is necessary to check whether an element belongs to a certain class or not. The hasClass() function will help you do this:

$(‘p:first’).hasClass(‘supriseMe’)

If any element in the set belongs to the specified class, the function will return true.

3.3 Setting the content of elements. 3.3.1 Replacing HTML or text. The most simple command– html() – returns us the HTML code of the first matching element if the parameter was not specified, or sets the HTML fragment passed as a parameter to the contents of all selected elements.

Also, it is possible to get only the text content of elements. There is a text() command for this.



  • Three

  • Four

Var text=$("#theList’).text();

As a result, the text variable will contain the string "OneTwoThreeFour".

As with the previous function, we can set the text content for an element by providing the test() function with the required text as a parameter. Moreover, if the text contains characters< или >they will be replaced with special characters.

It's worth noting that using these two commands to set the contents of elements will remove the previous content, so use these commands carefully.

3.3.2 Moving and copying elements. To add content to the end of existing content, use the append() command.

The function appends a string or HTML fragment passed to it as parameters to a new or existing DOM element, or to a set of nested jQuery elements. Let's look at a few examples.

$("p").append("some text");

This expression will append the HTML fragment created from the string passed to the function to the end of the already existing content of all elements

On the page.

A more complex use of this command allows you to designate existing DOM elements as children of other elements. That is:

$("p.appendToMe").append($("a.appendMe"))

Allows you to assign all links of the appendMe class child elements everyone

To the appendToMe class page. In this case, the final position of the assigned elements depends on the number of target elements. If there is only one, then the assigned elements will be moved from their original position on the page, but if there are several target elements, then the assigned elements will remain in their original place, and their copies will be assigned to the target elements.

To move or copy an element from one location to another, you can also use the appendTo() command, which moves all elements of a nested set to the end of the contents of the target element specified as a function parameter. Let's look at the example to see the difference from the previous function:

$(" a.appendMe").appendTo($("p.appendToMe "))

The target can again be either a selector or a DOM element. As in the previous function, if there is only one target element, then a move operation will be performed, if there are several target objects, then copying will be performed.

The following commands work in a similar way to append() and appendTo():
prepend() and prependTo() – inserts source element before the target, not after.
before() and insertBefore() - inserts an element before the target elements, not before the first child.
after() and insertAfter() - inserts the element after the target elements, rather than after the last child.

Let's consider next example:

$(‘

Hello!

').insertAfter('p img');

This expression will create a new paragraph and insert copies of it after each picture within the paragraph.

3.3.3 Nesting Elements Another type of DOM manipulation that we often turn to is nesting elements (or a group of elements) within some other element. For example, we might want to put all references of a particular class inside . This can be done using the wrap() command. This method nests the selected set of elements inside the passed HTML code or a clone of the passed element.

$(“a.surprise”).wrap(“”);

$(“a.surprise”).wrap($(“div:first”));

What should we do if we need to place all the selected elements not one by one, but together in some kind of common container? The wrapAll() function will help us with this.

Well, when we want to place not every element, but only its contents, in the container we need, we use the wrapInner() function.

3.3.4 Removing Elements If we want to clear or remove a set of elements, this can be easily done using the remove() command, which removes all elements of a nested set from the DOM of the page.

It is worth considering that, like many other jQuery commands, the result of this command is again a set of elements. And even though we have removed it from the DOM, we can still use it further in other functions, for example, the same appendTo() or insertAfter() or other similar ones.

To clear elements of their contents, you can use the empty() command. It removes the contents of all DOM elements in the set.

It is common to use remove() and after() for the replacement operation. This is done like this:

$(‘div.elementToReplace’).after(‘

I'm replacing the block

').remove();

Since after() returns the original element, we can simply remove it, leaving only the new paragraph

If you like the idea, you can refine it and write the following function:

$.fn.replaceWith = function(html) (
return this.after(html).remove();
}

Then we will perform the previous operation like this:

$(‘div.elementToReplace’).replaceWith(‘

I'm replacing the block

’);

But what to do when we don’t want to move elements, but only copy them?..

3.3.5 Cloning elements To do this, jQuery has the clone() command. It creates and returns a copy of the set. All elements and children are copied. If the true parameter is passed, all handlers are also copied.

Cloning elements has little effect until we do something with the copy. Here everything depends on our imagination. Here are a couple of examples:

$('img').clone().appendTo('fieldset .photo');

This expression makes a copy of all images and places them in all elements of the photo class.

One more example:

$(‘ul’).clone().insertBefore(‘#here’);

Performs a similar operation. It is worth noting here that all elements are cloned

    , including their descendants
  • (if there are any, of course).

    And the last example:

    $(‘ul’).clone().insertBefore(‘#here’).end().hide();

    This expression is similar to the previous operation, but after inserting the copy, the end() command selects the original set, after which it is hidden with the hide() command.

    3.4 Operations with form elements The main action that is performed with forms is working with their data. The val() command returns the contents of the value attribute of the first element in a set. When a form element contains multiple choices, an array of the values ​​of all those choices is returned.

    This command, although quite useful, has a number of limitations. If the first element of the set is not a form element, we will receive an error message. Also, this command does not distinguish between checked and unchecked elements of checkboxes or radio buttons.

    For the case of a radio baton, you can proceed as follows:

    $(‘:checked’).val()

    This expression will return the value of the only selected radio button named radioGroup (or will return the value undefined if no radio button was selected). This example cannot be applied to checkboxes because there can be more than one selected value, and as stated, val() returns the contents of the value attribute of the first element in the set.

    When passing a parameter to the command, it will be set as the value for all selected elements of the set. However, again there are a number of limitations. For example, you cannot set multiple values ​​for a multiple selection item.

    Another use for val() is setting checkboxes and radio buttons or selecting options. This passes an array of values, and if any of them matches the element's value, the element will be selected (checked). For example:

    $('input,select').val(['one','two','three']);

    This expression will check all elements and whether their values ​​match any of the passed strings: one, two or three. If the values ​​match, the checkboxes or radio buttons will be marked and the select option will be selected.

    Another chapter has come to an end. Again, I will welcome healthy criticism. Thank you.

    Let me also remind you that you can always find this and other articles

    There are times when you may need to create a draggable element inside your web application. This is great functionality, however, you may want the element to remain in its new location after being dragged. In today's article, you will learn how you can easily drag and dock the desired element in a new location, even after a page reload, by capturing and storing its X and Y coordinates.

    Scenario

    So you have an element on the page. You can drag it back and forth. But when the page is reloaded, the element returns to its original position. And although we need the element to be draggable, we want our element to only need to be dragged once. Let's look at a simple solution that implements this functionality.

    Start

    For this example we will need the library and the JQuery-JSON plugin. Apart from this, we will also use PHP and a MySQL database to parse and store our data. If you're new to jQuery, don't worry. JQuery is an extensible, fast and lightweight JavaScript library that is easy and fun to use. The library has well-structured documentation and a huge community.

    HTML and CSS

    Let's start with the HTML markup and styles for our example. First the CSS:

    Html, body ( background:#151515; margin:0 0 0 0; padding:0 0 0 0; ) #glassbox ( background:#333; border:1px solid #000; height:400px; margin:30px auto auto auto; position:relative; width:960px; -moz-border-radius: 10px; -webkit-border-radius: 10px; ) #element ( background:#666; border:1px #000 solid; cursor:move; height:143px; padding:10px 10px 10px 10px; width:202px; -moz-border-radius: 10px; -webkit-border-radius: 10px; ) #respond( color:#fff; margin:0 auto 0 auto; width:960px; )

    CSS is very simple. We assign null properties to html and body to clear outer and inner padding, then set height, width and other properties for our elements. - moz-border-radius and -webkit-border-radius are two properties that allow us to create rounded corners(currently only works in Mozilla Firefox and Safari 3) for our elements. Now, let's take a look at the HTML:

    Simple Draggable Element Persistence with jQuery Move the Box

    As you can see, we have created a very simple page, which included our CSS, JavaScript library and plugins, in addition, the page contains elements to which we will apply some effects and events. Please note that the jquery-ui file is a custom build that only includes the core and drag-and-drop functionality.

    JavaScript

    Now comes the fun part! First let's look at basic functions, which we will use to apply some effects to our elements. Let's analyze everything to the core.

    $(document).ready(function() ( $("#element").draggable(( containment: "#glassbox", scroll: false ))

    First we tell the browser, “Hey, this is the code we want to run; It's not HTML, it's JavaScript." Then, we wait for the document to fully load, after this has happened, we call a function to get our #element block, and add a drag handler to it with basic settings. The containment option contains our element inside the parent block, and we set the scroll value to false because we don't need scrolling.

    Mousemove(function())( var coord = $(this).position(); $("p:last").text("left: " + coord.left + ", top: " + coord.top); ) )

    Inside this snippet, we call the mousemove event handler and tell it: “When the mouse moves, set the coord variable to the value current position of our block #element" We then get the last paragraph in the block #("p: last") and print text that prints the values ​​of the left(x) and top(y) properties of our element, relative to the parent object (which is the #glassbox block).

    Mouseup(function())( var coords=; var coord = $(this).position(); var item=( coordTop: coord.left, coordLeft: coord.top ); coords.push(item); var order = ( coords: coords ); $.post("updatecoords.php", "data="+$.toJSON(order), function(response)( if(response=="success") $("#respond").html ("X and Y Coordinates Saved!").hide().fadeIn(1000); setTimeout(function())( $("#respond").fadeOut(1000); ), 2000); )); )); )); lt;/script>

    Well, yes, this is more complicated. We're going to do a bunch of things in this snippet. First, we set up an empty array and then get some values ​​to fill it with. By calling the .mouseup() event handler, we tell the browser to listen for an event when you release the mouse button. We specify that the coords variable is an empty array and again set its value to the position of our #element block.

    Next, we need to create a list of two lines, which will be coordTop: and coordLeft:, corresponding to the left and top positions of our block. Using the line coords.push(item) , we will populate our list with an array of coordinates. Then we set the order variable as a new list in which the coords key will correspond to our coords array. Now a little Ajax.

    $.post is an AJAX request handler that loads deleted page, using the HTTP POST method. This function takes following parameters: url, date, response and data type to return. In this example, we'll point the file updatecoords.php as our URL because that's where we want to send our data. Next, we'll define the data type by including the $.toJSON function defined in the JSON plugin and assign the order variable to be the data that .toJSON should return.

    Next, we create a response that checks to return a successful response from our PHP file. If a successful response is received, we display a message about the successful saving of coordinates using the .fadeIn() method and a speed of 1000 milliseconds, then set a timer for 2000 milliseconds, and again slowly hide this message using the .fadeOut() method. This is what our JavaScript will look like in its entirety:

    $(document).ready(function() ( $("#element").draggable(( containment: "#glassbox", scroll: false )).mousemove(function())( var coord = $(this).position (); $("p:last").text("left: " + coord.left + ", top: " + coord.top); )).mouseup(function())( var coords=; var coord = $(this).position(); var item=( coordTop: coord.left, coordLeft: coord.top); coords.push(item); var order = ( coords: coords); $.post("updatecoords.php ", "data="+$.toJSON(order), function(response)( if(response=="success") $("#respond").html("X and Y Coordinates Saved!").hide( ).fadeIn(1000); setTimeout(function())( $("#respond").fadeOut(1000); ), 2000); )); )); ));

    Place this code below the HTML, right after the closing body tag.

    PHP

    Okay, let's do something with the data that comes from our JQuery. First you need to create simple base data to store our coordinates, which we will later use to determine the position of our element. Next, we will need a config.php file, which will record the parameters for connecting to the database, and then we will move on to updatecords.php.

    Database: "xycoords" CREATE TABLE IF NOT EXISTS coords (id int(11) NOT NULL AUTO_INCREMENT, x_pos int(4) NOT NULL, y_pos int(4) NOT NULL, PRIMARY KEY (id)) ENGINE=MyISAM DEFAULT CHARSET=latin1 ;

    Config.php

    updatecoords.php

    Everything is quite simple here. The first thing we do is check if the data has been transferred to the file. If this happens, we include our config.php settings file and assign the $data variable the value json_decode(passed post variable); json_decode is a PHP function introduced in PHP 5.2.0 that allows you to decode a JSON string.

    Since our $data variable contains an array of data, we need to parse it into pieces to get required values. To do this, we will loop through the $data->coords() array (which was obtained from the order variable in JavaScript) and process each element. As a result, from each key-value pair a list object will be created, which we will later specify and create a variable to display it. In this case, we will use the preg_replace function to exclude unnecessary characters. Additionally, we will prepare our values ​​for insertion into the database by escaping quotes and apostrophes using the mysqli_real_escape_string function. If everything went well, we will need to return a successful JavaScript result.

    Finally

    Now that we have everything ready, in order to get the element's coordinates and pass them to PHP for writing, we will need to change our HTML markup to display the element's position. To do this, we'll remove the simple HTML markup and create it using PHP:







2024 gtavrl.ru.