user1561666
user1561666

Reputation: 79

How do I use jQuery to display an HTML element?

I have some code here that is supposed change display: none to display: block on 1 element when you mouse over another element.

HTML:

<li onmouseover="popup('Ipsum');">Lorem</li>

Javascript:

$(document).ready(function(){
    $("body").append('<div id="pup"></div>'); // Appends a popup div to the page
    $(document).mousemove(function(e){
        var x,y;                                   // This sets the mouse
                                                   // coordinates into 2
        x = $(document).scrollLeft() + e.clientX;  // variables in order to
        y = $(document).scrollTop() + e.clientY;   // display the tooltip
    });                                            // relative to mouse postition

    function popup(text)
    {
        $('#pup').html(text);  // This is supposed to enter text into the tooltip
        $('#pup').show();      // div and change it from display: none to
                               // display: block
    }

Currently, the div exists (however you can't see it because it is set to display: none in the CSS, but when you mouse over the li it isn't displayed. Thanks!

Upvotes: 3

Views: 177

Answers (1)

SomeShinyObject
SomeShinyObject

Reputation: 7801

I second Russ C's comment. Move popup out of $(document).ready, but not as a global function. Assign it as an anonymous function and give jQuery as a parameter.

Didn't know you wanted help with the mouse events. This one appears below the mouse. The "title" attribute can only hold plain text, so if you want something not so robust, go with that.

Try this

    $(document).ready(function(){
        var loremHTML = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. <a href=''>Vivamus non elit risus</a>, a dignissim ligula."
        $("#lorem").hover(function() {$.popup(loremHTML)},function() {$("#pup").hide().remove()});
        $(document).mousemove(function(ev) {
            $.mousePos = {      //Assign mousePos to the jQuery object
                x: ev.pageX,    //x coordinate
                y: ev.pageY     //y coordinate
            };
        });
     });   

     (function($) {
        $.popup = $.fn.popup = function(text) {
            $("body").append('<div id="pup"></div>');
            $('#pup').show().css({
                "position":"absolute",
                "left":$.mousePos.x,
                "top":$.mousePos.y})
                .html(text);
        }
     })(jQuery);

CSS

        #pup {
            background:#ddd;
            padding:5px;
            width:20%;
        }

HTML

<span id="lorem">Lorem</span>

Upvotes: 1

Related Questions