Drawing a function to <DIV> - javascript

Thanks for reading and helping. I'm trying to use a function that draws a Dial in a specific div but isn't working. I know this works for text:
<div id="content">
</div>
<script>
document.getElementById('content').innerHTML = "hi";
</script>
But what if i want to write some function there? How can i do that? Imagine i have this:
<div id="content">
</div>
<script>
document.getElementById('content').innerHTML = somefunction();
function somefunction(){
document.write("hi");
}
</script>
I know that if i use return it work's but i want to know if there's a way to do it without return.
Thank you so much!
EDIT:
I'm going to be more specific. Imagine i have this:
<div id="content">
</div>
<script>
function createDial(){
document.write("<input class='knob' data-min='-15000' data-max='15000' value='-11000'>)
}
</script>
That input creates a Dial (see http://anthonyterrien.com/knob/ if you don't know that i'm refering to). Now, having this, can i a draw the Dial in "content"?
Thanks all and i'm sorry for my english!

Return string for somefunction instead of document.write
function somefunction(){
return "hi";
}
You can pass element name to function and assign html in to element there.
function somefunction(elementId){
document.getElementById(elementId).innerHTML = "hi";
}

If you really need to get this work without returning a value, you can do something like this:
function somefunction (elm) {
elm.innerHTML = '<input class="knob" data-min="-15000" data-max="15000" value="-11000">';
$(".knob").knob();
}
somefunction(document.getElementById('content'));

All i needed is this (I think Yoshi referred to this too):
$( "#content" ).append("whatever you want, even an input or something else");
That's why I tagged with jQuery before.

Related

Variable value not accumulating?

Hey I'm very new to JS but cannot figure out why the 3 variables at the top aren't accumulating?
var xe = 0;
var reckon = 0;
var books = 0;
document.getElementById('#go').addEventListener('click', function(){
questionOne();
});
document.getElementById('#macos').addEventListener('click',function(){
addXe();
questionThree();
});
document.getElementById('#windows').addEventListener('click',function(){
questionThree();
});
document.getElementById('#linux').addEventListener('click', function(){
questionThree();
});
document.getElementById('#large').addEventListener('click', function(){
questionFour();
addXe();
});
function addXe(){
xe++;
};
function addReckon(){
reckon++;
};
function addBooks(){
books++;
};
The rest of the code is simply a series of functions that toggles divs display on and off.
If Ive missed and important info out let me know,
Thanks!
EDIT:
github.com/daffron/accountingsoftware
I thought it would be easier to attach the whole site, the problem is each time the addXero function is executed , it doesn't accumulate the value of var xero, I have it printing to console in the other functions. Thanks –
Your parameters for document.getElementById() are wrong.
If your HTML code for a button is like this:
<input type="button" id="go" />
<!-- OR like this: -->
<button id="go" ></button>
Then your javascript code must access the button using the method getElementById() as:
document.getElementById("go");
So, one of your functions will be like:
document.getElementById('go').addEventListener('click', function(){
questionOne();
});
BUT, if you've used '#go' because you were referring to a CSS Selector then you've to use querySelector method instead of getElementByIdas:
document.querySelector("#go");
So, a function call as per your code will be:
document.querySelector('#go').addEventListener('click', function(){
questionOne();
});
you should have html label example
<label id="xeLbl">test</label>
and after changing value you should apply it to html label.
function addXe(){
xe++;
document.getElementById('xeLbl').innerHTML = xe;
};

jQuery reset star-rating.js

I am using this plugin https://danielupshaw.com/jquery-star-rating/
I want to reset my form. But how can I reset these stars??
$("#btn-reset").on('click', function() {
//some other inputs reset
$('#starrating').star_rating.remove();
$('#starrating').star_rating.reload();
}
Please help on how to reset these stars to zero or null.
Here is the full code.
$("#btn-reset").on('click', function() {
$('#starrating').star_rating.reload();
});
jQuery(function($) {
$('#starrating').star_rating({
click: function(clicked_rating, event) {
event.preventDefault();
$('input[name=\'rating\']').val(clicked_rating);
this.rating(clicked_rating);
}
});
});
I don't know if this is the best approach, since I'm not familiar with this library...
But I achieved a reset like this:
$(document).ready(function(){
$('.rating').star_rating();
$("#resetStars").on("click",function(){
$(".rating").remove();
$('.star-rating').replaceWith("<span class='rating'>0/10 stars</span>");
$(".rating").text("0/10").star_rating();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://danielupshaw.com/jquery-star-rating/jquery.star-rating.js"></script>
<h1>This is a good script!</h1>
<span class="rating">9.5/10 stars</span><br>
<br>
<br>
<button id="resetStars">Reset stars</button>
I'm not familiar with the plugin, but looking at the link you provided, can't you just update the text inside of the element to reflect an empty or zero rating? Something like:
$("#btn-reset").on('click', function() {
$('#starrating').text('0/5').star_rating();
}
It looks like all you need to do is set the content to 0. Then re initialize the method.
$("#starrating").html("0");
$("#starrating").star_rating();
You could try something like this; an attempt to set default blank stars on initial page load, or Click.
$(document).ready(function() {
$('i').addClass('fa-star-o');
});
Then refresh page to rest:
$( ".reset" ).click(function() {
location.reload();
});
If you don't want to refresh page, you could try:
$( ".reset" ).click(function() {
$('i').addClass('fa-star-o');
});
You may have to re-initiate your click feature on the star with similar jQuery to re add the appropriate Class when needed.
If this doesn't help or work; could you create a https://jsfiddle.net/ to fully replicate your issue; and then we could solve it. If it were me; I'd find a better plugin to use or just write it from scratch at that point.
A bit another approach by re-rendering your rating stars from scratch using custom renderRating function.
HTML:
<div class="rating-stars"></div>
<button class="reset-rating">Reset rating</button>
JS:
var defaultRating = "0/5";
renderRating("3/5");
function renderRating(rating) {
var ratingEl = $('<span />').addClass('rating');
var ratingStr = rating || defaultRating;
ratingEl.text(ratingStr);
$('.rating-stars').html(ratingEl);
ratingEl.star_rating();
}
$('.reset-rating').on('click', function() {
renderRating();
})
Preview on JSFiddle
This should reset it to 0:
$('#starrating').star_rating('rating', 0);
Here's the format to call the public methods:
$('#starrating').star_rating('method_name');
Should your click event be inside the document ready? If it is outside document ready, that can sometimes cause issue. I hope this helps :)

$(this) acts like both event and <div>

I'm a long-time procedural programmer now assigned to a web-app and studying jquery from a book. The exercise is to run some code on one div selected from a row of 4 <div>s using .each(). I attempted to store the div object that was clicked, then match it as the .each looped thru the 4 divs.
My following code works after trial and error, but the same $(this) seems to sometimes point to a div object, and sometimes to an event object.
How do you explain that behavior?
I understand that .context is deprecated. I tried .target but that didn't seem to work. Is there something else that I should be using?
My primary interest is to understand what is going on (question 1), so if you can provide an explanation and not just an alternative solution (question 2), I'd really appreciate it. Thank you in advance. Here are the code snippets:
<body>
<div id="header">
<h2>Jump for Joy Sale</h2>
</div>
<div id="main">
<div class="guess_box"><img src="images/jump1.jpg"/></div>
<div class="guess_box"><img src="images/jump2.jpg"/></div>
<div class="guess_box"><img src="images/jump3.jpg"/></div>
<div class="guess_box"><img src="images/jump4.jpg"/></div>
</div>
<script src="scripts/jquery-1.6.2.min.js"></script>
<script src="scripts/my_script.js"></script>
</body>
Jscript
$(document).ready(function()
{
$(".guess_box").click(checkForCode);
function checkForCode()
{
var code_box = 2;
var discount_code = getRandomNum(1,100);
var clicked = $(this); // debugger says clicked is an event object
var iteration = 0;
$(".guess_box").each(function()
{
if ($(this).context === $(clicked).context) //act like event objs
{
if (iteration === code_box)
{
// clicked on correct box
$(this).addClass("discount"); //same $(this) acts like <div>
discount_msg = "<p>Your Code: CODE"+ discount_code +"</p>";
return(false);
}
}
else
{
if (iteration === code_box)
{
// if wrong box clicked, highlight the right one
$(this).addClass("no_discount");
discount_msg = "<p>Sorry, no discount this time</p>";
return(false);
}
}
iteration += 1;
});
$(".guess_box").unbind();
$(this).append(discount_msg); // don't worry about this line
} //checkForCode
}); //ready
The context of this depends on where and how it's used. if your function is called by an an event it will refer to the target of the event, otherwise it will refer to the object being called upon.
What youre seeing in your console is not this, or an event object, it's a jQuery object. If you want to inspect this you need to remove the jQuery wrapper function.
console.log(this);
Event example..
<div>click me</div>
$("div").click(function(){
// referring to the div itself
$(this).text("you clicked me");
// Note you can do it without jQuery as well
// this.innerHTML = "you clicked me";
});
object example
function something(){
this.something = "something";
this.doAThing = function(){
this.something = "something new";
}
}
var thing = new something();
thing.doAThing();
alert(thing.something);
Thanks to those that responded. As Pamblam indicated, I was confusing this and $(this). I replaced 2 lines in my code and it makes more sense:
clicked = $(this) becomes clicked = this
if ($(this).context === $(clicked).context) becomes
if (this === clicked)

How to use the title attribute of a div to add a class?

I'm trying to add a class to a div by using the title attribute. Currently the alert is correct. However the class isn't added.
JS Part:
function index(clicked_id){
alert(clicked_id);
$('#sticky').attr("title", +clicked_id).addClass("glow");
}
HTML Part:
<div id="sticky" class="" title='sticky1' onclick='index(this.title)'</div>"
I don't know if I got your question right but I understood that you want to filter|find you div by the title. So maybe this code will help you:
function index(clicked_id){
alert(clicked_id);
$('#sticky [title="' + clicked_id + '"]').addClass("glow");
}
This is how I would do it:
$("[title*='sticky']").click(function(){
$(this).addClass("glow");
});
Here is the JSFiddle demo
Why do you need to do it like that? Can't you just set the class on the element clicked?
JavaScript
function index(el){
$(el).addClass("glow");
}
HTML
<div id="sticky" onclick='index(this)'></div>
Instead just pass this:
onclick='index(this)'
now in the function:
function index(el){
var e = $(el).attr('title');
$('#sticky[title="'+e+'"]').addClass("glow");
}
As the element itself is the target one then just use this:
function index(el){
$(el).addClass("glow");
}
or better to go unobtrusive, remove the inline event handler and use this way:
$('#sticky').on('click', function(e){
$(this).addClass("glow");
});
js at Question returns expected results. Missing closing > at html #sticky <div> tag at
onclick="index(this.title)"
following onclick attribute . Additionally,
+
should be removed at
+clicked_id
at .attr() setting title . javascript + operator attempting to convert clicked_id String to Number when placed before string
function index(clicked_id){
alert(clicked_id);
$('#sticky').attr("title", clicked_id).addClass("glow");
}
.glow {
color: purple;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="sticky" class="" title="sticky1" onclick="index(this.title)">click</div>

How to tell jQuery that all selectors I write should be limited to the object being worked on?

I made this incredible plugin that will change the fate of the world http://jsfiddle.net/4phfC/1/:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script>
$.fn.colorText = function(color) {
$('.bar', $(this)).css('color', color);
// a million other lines of code here...
}
$(function() {
$("#div1").colorText("red");
});
</script>
<div id="div1" class="foo" style="width:100px;height:100px;border:1px solid green">
<span class="bar">Hello</span>
</div>
<div id="div2" class="foo" style="width:100px;height:100px;border:1px solid green">
<span class="bar">Good Bye</span>
</div>
In order to effect just the span tag with the class "bar" that is within the object that I attached the plugin to and not the other one on the page I did:
$('.bar', $(this)).whatever();
But notice the spot where the million other lines of code will go, it would be somehwat of a pain to use this convention throughout the rest of the plugin.
Is there any way to tell jQuery from now on all selectors I declare are applicable only to the element that the plugin is attached, so that I can use selectors like normal:
$('.bar').whatever();
and this won't affect any ".bar"'s that are outside of the element being worked on.
I agree with all of the comments about caching selectors, but if you still really wanted to do something like you are describing, you could always encapsulate the functionality in another function.
$.fn.colorText = function(color) {
var that = this;
function selectInScope(selector) {
return $(selector,that);
}
selectInScope('.bar').css('color', color);
// a million other lines of code here...
}
No, not that I know of, but you could do this:
$(this).find('.bar')
If you really wanted to, you could do something like this:
!function($) {
function jqScoped(scope) {
return function() {
return $.apply(window, Array.prototype.slice.call(arguments).concat([scope]);
};
}
var jqUnscoped=$;
$.fn.colorText=function(color) {
var jQuery=jqScoped(jqUnscoped(this)), $=jQuery;
$('.bar').css('color', color);
};
}(jQuery);
...but that might not work for non-selector arguments to $ (although I haven't tested it).
While there might not be a selector, you can save a jQuery object as a variable, and use it from then on in. For example...
$.fn.colorText = function(color) {
var thisBar = $('.bar', $(this));
thisBar.css('color', color);
// continue to use thisBar...
// a million other lines of code here...
}

Categories

Resources