addClass and class to be added is part name and part variable - javascript

Working with the YUI library and I have the following:
var levelnumber = 3;
I want to add a class to a div so that it says ".level3" , so the class to be added should be the word "level" plus the value of the variable.
Something like this but Im not sure on the syntax:
addClass("level"+[levelnumber]);
I have tried quite a few combinations of single and double quotation marks but cant get it to work.
Thanks!
EDIT:
Sorry fellas!
I asked the wrong question.
I have that part sorted actually, my problem is not with adding the class, it is with selecting a class!
I want to select .group .level3
var level = 3;
Y.all(".group" '.level'+[levelnumber])
That is what I have now but don't know where all the quoatation marks should go.
Thanks!!

Just remove the square brackets. As long as one of the variables is a string, it will concatenate them together. Here's a good article on strings in JavaScript.
addClass('level'+ levelnumber);

check this out
<div id="foo" class="bar">foo</div>
<script type="text/javascript">
var addClass = function(level) {
YAHOO.util.Dom.addClass('foo',"level"+ level );
};
addClass(3);
</script>

Related

HTML button tag removal from backend

I have created a button dynamically in JavaScript and i am deleting the same when user clicks X symbol on it..
I am setting style.display=none to achieve this but the problem is in HTML there is space in it even after deleting the button. How can i delete the button without any space in HTML.
var x = document.getElementById(id);
x.style.display='none';
First of all, if you Google remove HTML element in javascript the first thing you see is this: How to remove an HTML element using Javascript?
and it works, but I'll pitch in my 2 cents anyways since that one uses parentElement, which is kinda outdated.
There's a .remove() method in javascript that lets you remove an html element.
It's as simple as:
var x = document.querySelector("#id");
x.remove();
but I doubt that will solve your issue, you might want to remove the parent element if it has a margin or padding like so:
var x = document.querySelector("#id");
x.parentElement.remove();
cheers
try it if u want to change the css
<script type="text/javascript">
$("#id").css('display', 'none');
</script>
or use it for add or remove the class. change the add to remove if want remove the class
<script type="text/javascript">
document.getElementById("submit").classList.add('disabled');
</script>

How to add user input to a JavaScript array

I am in the process of learning JavaScript and jQuery, so apologies if any of this sounds naive or obvious. I started what I thought was a fairly simple project to practice and hopefully learn something in the process.
What I want to do is this: the user inputs a sentence and hits a submit button. The sentence gets added to a list of other sentences submitted by people (preferably on a separate file, preferably encrypted, but not necessary). Then, the website grabs a random sentence from the list and displays it.
I am not asking on how to build all of this. I have already put most of it together, but I am including it here for reference.
I have a separate javascript file with the array of quotes.
var quotes=new Array();
quotes[0]="<p>Quote 1</p>";
quotes[1]="<p>Quote 2</p>";
quotes[2]="<p>Quote 3</p>";
quotes[3]="<p>Quote 4</p>";
quotes[4]="<p>Quote 5</p>";
quotes[5]="<p>Quote 6</p>";
quotes[6]="<p>Quote 7</p>";
Then I randomly display one using this:
function getQuote(){
var thisquote=Math.floor(Math.random()*(quotes.length));
document.write(quotes[thisquote]);
}
And adding <script> getQuote(); </script> to the html.
This all works fine.
The part I cannot seem to figure out is taking user input and adding it to the jQuery array. I am using a contenteditable div instead of an <input> because I want it to have multiple lines of text and have a character limit, which as far as I know can only be done with a contenteditable div (according to the research I did at the time, I may be wrong).
I have looked around and tried many if not all the examples I found of how to do this, and none of them worked. This is the last method I tried, if it helps:
$(".submit").click(function() {
quotes[quotes.length] = document.getElementsByClassName("input").value;
});
So, to reiterate, I want to take user input and add it to a JavaScript array. I have scoured stackoverflow and the interet but nothing has worked. Please help!
UPDATE: Arvind got it right. I still have a lot to learn, and it seems I need to read up on localstorage and cookies. I will also need to use PHP to save the sentences on the server. Thank you to all who answered!
Problem is document.getElementsByClassName("input") gives you a NodeList and not just a single html element. So if you do this document.getElementsByClassName("input").value, you will end up quotes as [undefined, undefined ... undefined]. Assuming you have single element with the class name input, go with index 0. Also as you stated that you are using div with attribute contenteditable, you may try this instead. document.getElementsByClassName("input")[0].innerHTML
Try this example.
var quotes = localStorage.getItem('quotes'); //get old, if any, gives you string
quotes = quotes ? [quotes] : []; // if got quotes then make it as array else make new array
$(function() {
var quote = $('#quote'); //get the quote div
quote.html(quotes.join('') || quote.html()); //set the default text
$('#btn').on('click', function(e) {
quotes.push(quote.html());
localStorage.setItem('quotes', quotes.join('')); //save the quotes
alert(quotes.join(''));
});
});
#quote {
border: 1px solid grey;
height: 100px;
overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div contenteditable='' id='quote'>
<ol>
<li>Quote 1</li>
<li>Quote 2</li>
</ol>
</div>
<input type='button' id='btn' value='Submit' />
P.S.
In order to preserve the old quotes you may possibly use cookie, localStorage, etc.
Are these "quotes" being saved locally?
Yes, to share it among several users visiting by different browsers, you have to save it with the server script like PHP, Java, ASP, etc. Here you can either use ajax, if you wana avoid page reload on submit, else you can go for form submit.
$(".submit").click(function() {
quotes[quotes.length] = document.getElementsByClassName("input").value;
});
should be
$(".submit").click(function() {
quotes.push(document.getElementsByClassName("input").text());
});
EDIT: With a content editable div you need to use text() instead. Here is an example fiddle. https://jsfiddle.net/
var quotes=[];// better
// function to add to array
function addQuote(myquote){
quotes.push('<p>'+myquote+'</p>');
}
addQuote("Quote 1");
addQuote("Quote 2");
addQuote("Quote 3");
addQuote("Quote 4");
addQuote("Quote 5");
addQuote("Quote 6");
addQuote("Quote 7");
addQuote("Quote 8");
$(".submit").on('click',function() {
addQuote(document.getElementsByClassName("input")[0].value);
});
NOTE: suggest NOT using the "input" class name and use some other one as that might be confusing to others at some point later (confused by element named input)
I also added the paragraph tags as that would provide a consistent pattern for your input text. Assumption on my part however.
NOTE I also assume that the element IS an input type with the .value since that is NOT provided (the markup)

Change blockquotes when selecting faces

I have bunch of code already written (JS fiddle project) and I'm almost done, but I need some kind toggle thing i JS when you click a person's face, then the quote (scroll down at the result if you can't see it) will change to that person's quote.
I've already got a switch in the JS with this part:
$(function() {
var $profiles = $("#profile1, #profile2, #profile3, #profile4, #profile5, #profile6, #profile7, #profile8, #profile9, #profile10, #profile11");
$profiles.click(function(e) {
$profiles.removeClass("focused");
$(this).addClass("focused");
});
});
but I need to combine it with the quotes somehow.
If you really don't want to help me out with specific, I'd be just happy with just pseudo code or help on how to think. I've been sitting with this piece for way too long now to be able to think straight.
What would you recommend?
Cheers all, you guys rock!
I solved your problem like this:
$profiles.click(function(e) {
var profileNr = parseInt($(this).attr("id").substring(7));
$profiles.removeClass("focused");
$(this).addClass("focused");
$(".thequote .show").removeClass("show");
$(".thequote blockquote").eq(profileNr-1).find("p").addClass("show");
});
It extracts the index of the quote from the profile number and then selects the appropriate quote with jQuery eq(). I updated your JS Fiddle as well and tested that it works.
You have to have some kind of reference in your blockquote, for example a data attribute which indicates to which profile the quote belongs. For example:
<blockquote data-profileid="profile8">
<p>
"Sist är starkast... eller något sånt."
</p>
</blockquote>
Then in the onclick function, show the blockquote with the data attribute that matches the clicked id. You can get the clicked id like this:
var id = $(this).attr('id');

Making a javascript call work for multiple div boxes

I've got the following JavaScript code, which works great for the divs "from" and "copy" (when the user clicks "copy" it copys from "from"). I'm using ZeroClipboard.
clip.addEventListener('mouseDown', function() {
var pre = document.getElementById('from');
clip.setText(pre.innerHTML);
});
clip.glue('copy');
However, I want this to work for multiple divs - now it only works for the first one. I'm no JS expert so I humbly ask of you to explain how to do this. I'll use PHP to name my divs from1, from2, from3 etc and copy1, copy2, copy3 respectively.
You want to use var divs = document.getElementsByTagName('div') and then iterate over the divs object.
Steve's answer will work for all divs on the page. Assuming you have some divs that you don't want copied, a better solution will be:
var pre = document.getElementsByClassName('copy');
Amd then using a for to itterate the resulting array.
for(i=0; i<pre.length; i++){
clip.setText(pre[i].innerHTML);
}

How to swap two div tags?

I want to swap two html div tags entirely, tags and all. I tried the code below code but it does not work.
jQuery('#AllBlock-'+Id).insertAfter('#AllBlock-'+Id.next().next());
How to swap two div tags entirely.
You have some bracket mismatching in your code, it looks like you might be trying to do this:
jQuery('#AllBlock-'+Id).insertAfter($('#AllBlock-'+Id').next().next());
Which would take something like:
<div id="AllBlock-5"></div>
<div id="AllBlock-6"></div>
<div id="AllBlock-7"></div>
And, if called with Id 5, turn it into this:
<div id="AllBlock-6"></div>
<div id="AllBlock-7"></div>
<div id="AllBlock-5"></div>
This is because you're taking block 5, and moving it (using insertAfter) to the place after the block that's next().next() (or next-but-one) from itself, which would be block 7.
If you want to always swap #AllBlock-Id with #AllBlock-[Id+2], so they switch places and end up like the following:
<div id="AllBlock-7"></div>
<div id="AllBlock-6"></div>
<div id="AllBlock-5"></div>
You might want to try:
var $block = jQuery('#AllBlock-'+Id);
var $pivot = $block.next();
var $blockToSwap = $pivot.next();
$blockToSwap.insertBefore($pivot);
$block.insertAfter($pivot);
You can't do this because you can't concatenate a string and a jQuery object.
Try this:
var div = $('#AllBlock-'+Id);
div.insertAfter(div.next().next());
it should be like this
you should close the bracket after Id,
jQuery('#AllBlock-'+Id).insertAfter('#AllBlock-'+Id).next().next());
You'll need to detach the existing dom object first, then re-use it later:
$('#divid').detach().insertAfter('#someotherdivid');
What I understand is you want to swap a div when clicked with the last div. What will you do if it is the last div? move it to the top?
This solution should solve the problem, furthermore, you can modify this regex to match the format of your ID. This can probably be made more concise and robust. For example, you could get the last ID a bit more sophisticatedly. This may just be modifying the selector or something more. I mean, you do not want to go rearranging the footer or something just because its the last div on the page.
$('div').click(function() {
//set regex
var re = /(^\w+-)(\d+)$/i;
//get attr broken into parts
var str = $(this).attr('id').match(re)[1],
id = $(this).attr('id').match(re)[2];
//get div count and bulid last id
var lastStr = $('div:last').attr('id').match(re)[1],
lastID = $('div:last').attr('id').match(re)[2];
//if we have any div but the last, swap it with the end
if ( id !== lastID ) {
$(this).insertAfter('#'+lastStr+lastID);
}
//otherwise, move the last one to the top of the stack
else {
$(this).insertBefore('div:first');
} });
Check out this working fiddle: http://jsfiddle.net/sQYhD/
You may also be interested in the jquery-ui library: http://jqueryui.com/demos/sortable/

Categories