user4065758
user4065758

Reputation: 319

Write text over div without using .text()

I've got again a rather simple question, that I couldn't find an answer to.

I was using sofar the Jquery function .text() to write text on mouseenter on a dynamically created div. I came to realise that this only worked on my Iceweasel, but not in Chrome for instance. Instead ot .text() everywhere people advised of using the .val(), but I can't seem to figure out exactly how to use it in my implementation, since the divs had no previous text value.

Please find below a simple code, with .text() to understnad the question.

(function(){
    for (var i = 0; i < 3; i++) {
        var span = document.createElement("span");
        span.innerHTML = "<img width=\"" + data.size[i][0] + "\" height=\"" + data.size[i][1] + "\" id=\"" + i + "\">";
        span.style.position = "absolute";
        span.style.left = data.coords[i][0] + "px";
        span.style.top = data.coords[i][1] + "px";
        document.body.appendChild(span);
    }
}());

for (var i=0; i<3; i++) {
    $('#' + i).mouseenter(function() { 
         $(this).text("text");  
    });
    $('#' + i).mouseleave(function() { 
         $(this).text("") 
    });
}

http://jsfiddle.net/ckpx6esj/1/

I hope someone can give me an idea, of how to apply .val() or use something else entirely to make this work for chrome also.

Best Regards and Thanks in advance!

Upvotes: 2

Views: 175

Answers (5)

talsibony
talsibony

Reputation: 8756

First I will use class instead id, it will save using the second loop, also if you want to have also text and also image you can do it but it will be littel complicated I would recommand add some child element to the span that will contain the text, I didnt do it just for the challenge http://jsfiddle.net/ckpx6esj/5/

simple plugin to change the text without changing the html elements

$.fn.selectorText = function(text) {
    var str = '';

    this.contents().each(function() {
        if (this.nodeType === 3) {
            if(typeof(text) === 'string'){
                this.textContent = text;
                return false;
            }else{
                str += this.textContent || this.innerText || '';
            }

        }
    });

    return str;
};


var thisData = [{
    'coords' : [[100,100], [300, 300], [200, 200]],
    'size' : [[30, 30], [30, 30], [30, 30]]
}];
var data = thisData[0];

(function(){

    for (var i = 0; i < 3; i ++){
        var span = document.createElement("span");
        span.setAttribute('class','spanImage');
        span.style.position = "absolute";
        span.style.left = data.coords[i][0] + "px";
        span.style.top = data.coords[i][1] + "px";
        span.innerHTML = "\n<img width=\"" + data.size[i][0] + "\" height=\"" + data.size[i][1] + "\" id=\"" + i + "\">";
        document.body.appendChild(span);
    }


$('.spanImage')
  .on( 'mouseenter', function() {
   $(this).selectorText('text');    
  })
  .on( 'mouseleave', function() {
   $(this).selectorText('');
  });
}());

Upvotes: 0

Siguza
Siguza

Reputation: 23840

The problem is that you put text in an image tag!

<img>Some text</img>

This is invalid HTML, see this answer.

If you want text over an image, I suggest using a div with background: url(...) instead.

Updated fiddle.

Upvotes: 2

briosheje
briosheje

Reputation: 7446

The cleverest I could think to don't screw up your for loop is appending a <p> tag containing your text and removing it on mouseleave:

for (var i=0; i<3; i++){
                $('#' + i).on("mouseenter",function() { 
                        $(this).parent().append("<p>text</p>"); 
                    });
                $('#' + i).on("mouseleave",function() { 
                        $(this).parent().find("p").remove(); 
                });
}

Fiddle:

http://jsfiddle.net/ckpx6esj/2/

Besides, text was not working because you are listening to the image (<img>) instead of the span. Images has no .text() prototype, hence you should access its parent() (which is a <span> in that case) if you want to use the .text() prototype, but using .text() on the parent will remove the image, hence the idea of appending the text and removing it later.

Upvotes: 1

RuubW
RuubW

Reputation: 556

If you want the jQuery equivalent of Javascript's native innerHtml, go for $(this).html('text');.

Take a look at these functions:

http://api.jquery.com/html/

$(this).html('text');

http://api.jquery.com/append/

$(this).append('text'); // Note that this appends instead of replaces

http://api.jquery.com/val/

$(this).val('text');

Or if you're feeling adventurous:

http://api.jquery.com/appendto/

$('text').appendTo($(this)); // Performance penalty for creating an object out of 'text'

Upvotes: 0

suvroc
suvroc

Reputation: 3062

According to specification, val() function is to set value attribute and it only matters for input fields on your page. text() function is to change content of your element.

The .val() method is primarily used to get the values of form elements such as input, select and textarea.

So you should use text() function in your code.

Also according to your code you change text property of <img> element. This is not good. You should change text of your <span>. So just move your id to span element.

Upvotes: 0

Related Questions