Using variables within css javascript method - javascript

Anyone see what I'm doing wrong here? Creating circles using jQuery and then filling them with a variable from an input field.
The issue: The variable firstletter is is not being displayed when 1. there's input in the input box and 2. when the result pane is clicked to generate a circle. The variable should be in the middle of the circle.
jQuery:
// making of the circles
$('<div/>').attr({
'id': i
}).addClass('circle').css({
'top': e.pageY - 75,
'left': e.pageX - 75,
'content': firstletter
}).appendTo('#area');
firstletter being a variable here which I am using with the content css property.
Here's the fiddle:
http://jsfiddle.net/hslincoln/ZM7dC/

Need to use .val() instead of .text() and add the firstletter as the content of the div since https://developer.mozilla.org/en-US/docs/Web/CSS/content
Demo:http://jsfiddle.net/robschmuecker/ZM7dC/7/
var i = 0;
$('#area').bind('click', function (e) {
// input stuff
$('#jibberjabber').val(
function (index, value) {
var jimmy = value.substring(1);
return jimmy;
});
// push letter to variable ready for circle
var jibberjabbercontent = $('#jibberjabber').val();
var firstletter = jibberjabbercontent.charAt(0);
console.log(jibberjabbercontent, firstletter);
// making of the circles
$('<div>' + firstletter + '</div>').attr({
'id': i
}).addClass('circle').css({
'top': e.pageY - 75,
'left': e.pageX - 75
}).appendTo('#area');
i++;
});

Have updated the fiddle as per your requirement.
the problem is, you used text() instead of val().
jQuery
$('#'+i).html('<span class="charIn">'+firstletter+'</span>');
css
.charIn{
position:absolute;
top:47%;
left:46%;
}
used the above code to add the letter inside the span to make the letter appear center of the cirlce.
here is the working fiddle

Content can only be used with pseudo tags. Since the circle divs are not, the content is simply not displaying. Instead use
.addClass('circle').css({
'top': e.pageY - 75,
'left': e.pageX - 75,
}).text(firstletter).appendTo('#area');
Also you can't use .text to grab jibberjabber content. Instead use .val

Quote from W3Schools:
The content property is used with the :before and :after pseudo-elements, to insert generated content.
You don't have either of those, so the content is going nowhere.
#RobSchmuecker The OP wants the letter to be in the center. Also, your code skips the first letter.

Related

JavaScript adding to a variable and displaying result in a div

I'm just learning the basics of javaScript and jquery and have tried to put together this simple program http://codepen.io/mike-grifin/pen/oXjVYW. It's simply a box that displays a number and there is two buttons, one adds 10 and the other button subtracts 10. Ive set the output to alert and it seems to be working fine but if I remove the alert (below) it's not inputting the results into the container div.
$(document).ready(function(){
var startPoint = +90;
$(document).find('#container').append(startPoint);
if($('.increase').click(function(){
startPoint += +10;
}));
I've also tried to append the startPoint var again but it doesn't overwrite the original:
$(document).ready(function(){
var startPoint = +90;
$(document).find('#container').append(startPoint);
if($('.increase').click(function(){
startPoint += +10;
$(document).find('#container').append(startPoint);
}));
All the code is at the codepen link. I'm just learning so sorry if it's really obvious or easy. Any educational input or advice would be greatly appreciated. Thanks.
That's because you're appending the value to the #container element. If you want to directly alter the text, you can use jQuery's text() method:
$(document).find('#container').text(startPoint);
CodePen Demo
This will overwrite the current text with the new text you're passing in.
.text(text)
Set the content of each element in the set of matched elements to the specified text.
– jQuery's text() documentation
It's worth also noting that your if (startPoint >= 100) check will only be executed when your CodePen demo first loads. If you want to use this check, you'd need to place the if statement within your click event handlers.
You need to remove the contents before appending
i used empty()
$(document).ready(function(){
var startPoint = 90;
$('#container').empty().append(startPoint);
if($('.increase').click(function(){
startPoint += 10;
$('#container').empty().append(startPoint);
}));
if($('.decrease').click(function(){
startPoint -= 10;
$('#container').empty().append(startPoint);
}));
if(startPoint >= +100){
$('#container').empty().append(startPoint);
}
});
first of all .. for div you can use .text() or .html()
2nd .. move your if statement into .increase click event
$(document).ready(function(){
var startPoint = +90;
$(document).find('#container').append(startPoint);
$('.increase').on('click',function(){
if(startPoint >= +100){
alert('dayum!!');
}else{
$('#container').text(startPoint += +10);
}
});
$('.decrease').on('click',function(){
$('#container').text(startPoint -= +10);
});
});
You need to either set the .text() of the #container to the new value, or .empty() the old data out of it before you .append() any more.
$('.increase').click(function(){
$('#container').text(startPoint += +10);
});
Also, you don't need to wrap the $('.increase').click() in an if
It will fire when it is clicked, you don't need to say "if (this is clicked)"
It is implied by the .click() function
Read this : http://www.w3schools.com/jquery/html_html.asp And
.html() and .append() without jQuery
$(document).ready(function(){
var startPoint = +90;
$(document).find('#container').append(startPoint);
if($('.increase').click(function(){
alert(startPoint += +10);
$("#container").html(startPoint) //added
}));
if($('.decrease').click(function(){
alert(startPoint -= +10);
$("#container").html(startPoint) //added
}));
if(startPoint >= +100){
alert('dayum!!');
}
});
use this code, this helps you :)

Dynamically type a text inside a div using jQuery

My aim is to be able to type a text on the fly (that can be resized and move) inside a given div element, so I have created a textbox that is appended where i clicked.
$('div').click(function(e){
var top = e.clientY+'px';
var left = e.clientX+'px';
$('div').append('<input type="text">');
$('input[type="text"]').css({'position' : 'absolute','top' : top,'left' : left});
});
problem is that, when I was about to type a text, it won't let me and it created a new textbox instead.
Heres a fiddle to demo the problem.
Is there any clean approach as to what I wanted to do? Any suggestions is greatly appreciated. TIA
Use .focus() on input additionally.
Demo: http://jsfiddle.net/p2ct8eL7/4/
JS:
$('div').click(function (e) {
var top = e.clientY - 20 + 'px';
var left = e.clientX - 20 + 'px';
var i = $('<input type="text">'); //Store the input in a variable.
$('div').append(i);
i.css({
'position': 'absolute',
'top': top,
'left': left
}).focus(); // modify the current input instead of all.
});
When clicking, simply remove the click-Handler or check if there already is an input, so that your code can be skipped. Put this at the top of your event handler function:
if($(this).find('input[type="text"]').length > 0){
return;
}
Here's the fiddle: http://jsfiddle.net/p2ct8eL7/2/

ie8 appendchild not working

I am developing a website that must run on IE8.
I need to create a bunch of dynamic paragraphs since I am pulling data from a server at runtime.
To do so I am using the following code:
var tempAbstract = layerItems[iter].abstract; // string
var text1 = document.createElement('p'); // paragraph element
text1.textContent = tempAbstract; // assigning string to paragraph
$(text1).css({top: iter*25 + 30, left: 200, position:'absolute'}); // positioning
$(text1).css('color', 'black'); // make text color black
document.getElementById("listLayersWrapper").appendChild(text1); // appending to div
My problem is that the text won't render.
When I count the paragraph divs before and after I add the element, the counter increments as you would expect it should yet the text does not render. Additionally, when I get call position().left and position.top() the element also has the right coordinates.
I am not sure what I am doing wrong and have run out of options.
The issue doesn't appear to be with appendChild, but with textContent. According to the MDN page, textContent is only available in IE9 and up. Older versions of IE do have a non-standard innerText property you can use to achieve the same thing. Here is how you can implement this.
Example:
var tempAbstract = layerItems[iter].abstract;
var text1 = document.createElement('p');
if(text1.textContent !== undefined)
{
text1.textContent = tempAbstract;
}else{
text1.innerText = tempAbstract;
}
$(text1).css({top: iter*25 + 30, left: 200, position:'absolute'});
$(text1).css('color', 'black');
document.getElementById("listLayersWrapper").appendChild(text1);
Alternatively, this could be implemented in jQuery.
Example:
$('<p></p>')
.text(layerItems[iter].abstract)
.css({
top: iter*25 + 30,
left: 200,
position:'absolute',
color: 'black'
})
.appendTo("#listLayersWrapper");

jQuery: Removing Browser Generated Title Attribute

I'm attempting to remove the browser generated title box that appears with anchors that have a title attribute. The reason I want to do this is so it doesn't interfere with my tooltip jQuery.
As of right now I am removing the title attr on hover, but it won't reassign it after removing yourself from the hover state. How come?
http://jsfiddle.net/fj4xz/5/
Thats because the
var title
is in the HandlerIn function and not defined in the handler out.
Simplest solution is to put de var title outside of your hover function and assign it inside the hover handlers.
Edit: Removing the vars as stated by Photon is also a solution. I highly recommend you use vars though. Your code soon gets messy and unmaintainable if variables that are global are not defined. But thats just my opinion.
http://jsfiddle.net/RubenJonker/fj4xz/6/
That's because your title variable is within the mouseenter function, but you're using it inside mouseleave. You should move your title variable outside the hover method.
var title;
$('a.tooltip').hover(function() {
title = $(this).attr('title');
var offset = $(this).offset();
var width = $(this).outerWidth();
var height = $(this).outerHeight();
$content = $('<div class="tooltip">' + title + '</div>').fadeIn('fast');
$(this).append($content);
$(this).attr('title', '');
$content.offset({
top: offset.top + height,
left: offset.left + (width - $content.outerWidth()) / 2
});
}, function() {
$(this).find('div').fadeOut('fast');
$(this).attr('title', title);
});​
The reason why it won't re-assign the title value is because you're declaring the title variable in the first function, which is out of the scope of the second. If you want to preserve the original title value, you need to do so in such a way the second function has access to it.
Instead, try adding it to a data value:
$(this).data("originalTitle", $(this).attr("title"));
And then re-assign it within your second function:
$(this).attr("title", $(this).data("originalTitle"));
I would avoid having a generic title variable floating around that you're setting and getting for n links on the page. Storing the values as data on the element itself seems like a far better approach to me.
You're declaring var title = $(this).attr('title'); in your first function there, but your second function has no knowledge of title.
just remove all var declarations before variable name
it will become global variable See this
$('a.tooltip').hover(function() {
title = $(this).attr('title');
offset = $(this).offset();
width = $(this).outerWidth();
height = $(this).outerHeight();
$content = $('<div class="tooltip">' + title + '</div>').fadeIn('fast');
$(this).append($content);
$(this).attr('title', '');
$content.offset({ top: offset.top+height, left: offset.left+(width-$content.outerWidth())/2 });
}, function() {
$(this).find('div').fadeOut('fast');
$(this).attr('title', title);
});​

Combine js functions for input and textarea elements

So I need to add tooltips for some input fields and textareas. Currently, I have it setup like this:
$(document).ready(function(){
$('input').focus(function(){
var p = $(this);
var position = p.position();
var input_name = $(this).attr('id');
var name = '#'+input_name+'_help';
$('#apply_tooltip').css("left", position.left - 310 );
$('#apply_tooltip').css("top", position.top -15 );
$(name).show();
$('#apply_tooltip').show();
});
$('input').blur(function(){
$('.tooltip_inner').hide();
$('#apply_tooltip').hide();
});
$('textarea').focus(function(){
var p = $(this);
var position = p.position();
var input_name = $(this).attr('id');
var name = '#'+input_name+'_help';
$('#apply_tooltip').css("left", position.left - 310 );
$('#apply_tooltip').css("top", position.top -15 );
$(name).show();
$('#apply_tooltip').show();
});
$('textarea').blur(function(){
$('.tooltip_inner').hide();
$('#apply_tooltip').hide();
});
});
This works, but obviously there is probably a more efficient solution than simply duplicating the functions... Is there anyway to target both input fields and textareas with the same functions?
Instead of this:
$('input').focus(function(){
you can use this to get both types of objects with the same jQuery object and thus the same function:
$('input, textarea').focus(function(){
Though this isn't needed here, you ought to know that you can also put common code in a function and call that one function from multiple places rather than copying code into multiple places. Basically, you should pretty much never copy the same block of code into multiple places.
Another option is to refactor. In this specific case, jfriend00's answer is suitable, but if you needed to pass arbitrary arguments, e.g., the top or left positions, you can always pull out a method.
function tt(p) {
var position = p.position();
var input_name = p.attr('id');
var name = '#'+input_name+'_help';
$('#apply_tooltip').css("left", position.left - 310 );
$('#apply_tooltip').css("top", position.top -15 );
$(name).show();
$('#apply_tooltip').show();
}
$('input').focus(function() {
tt($(this));
});
$('textarea').focus(function() {
tt($(this));
});
My approach would be to do the alignment with CSS (with position: absolute if necessary) and set the tool tip to:
display: none;
Then in jquery you would only have to navigate the DOM and show/hide (or fadeIn fadeOut if you want to get sexy with it).
$('input').focus(function(){
$(this).siblings('.tip').show();
}).blur(function(){
$(this).siblings('.tip').hide();
});

Categories