jQuery .append() after offset - javascript

I have this:
<div id="testcase">abcdefghijklmnopqrstuvwxyz</div>
I would like to add this: <span> with an offset.
So when I for example would have the JS function: addSpan(4) this would happen:<div id="testcase">abcd<span>efghijklmnopqrstuvwxyz</div>
To visualise what I'm looking for:
function addSpan(i){
$('#testcase').append('<span>', i);
}

Use slice and concatinate...
function addSpan(i){
var content = $("#testcase").html();
var before = content.slice(0, i);
var after = content.slice(i + 1);
$("#testcase").html(before + "<span></span>" + after);
}

Here another wut i tired LIVE DEMO
$("#btn_clck").on('click', function () {
var gText = $("#testcase").html();
var getlength = gText.length;
var finalValue = "";
for (var i = 0; i < getlength; i++) {
var setData = gText.charAt(i);
if (i == 4) {
finalValue += '<span></span>'
}
finalValue += setData;
}
$("#testcase").text(finalValue);
});
but i think Steini's answers was better

Related

How do i switch Javascript to Jquery code?

I have some javascript that I want to convert to jQuery...
How do we change javascript to jquery code?
Do we just change the document.getElementById > $?
Do we change document.querySelectorAll > $ too?
Does the function portion also need to be tweak?
Kindly see my code apprehend below:
// Home Page Gallery
let i = 0; // current slide
let j = 5; // total slides
const dots = document.querySelectorAll(".dot-container button");
const images = document.querySelectorAll(".image-container img");
function next() {
document.getElementById("content" + (i + 1)).classList.remove("active");
i = (j + i + 1) % j;
document.getElementById("content" + (i + 1)).classList.add("active");
indicator(i + 1);
}
function prev() {
document.getElementById("content" + (i + 1)).classList.remove("active");
i = (j + i - 1) % j;
document.getElementById("content" + (i + 1)).classList.add("active");
indicator(i + 1);
}
function indicator(num) {
dots.forEach(function (dot) {
dot.style.backgroundColor = "transparent";
});
document.querySelector(".dot-container button:nth-child(" + num + ")").style.backgroundColor = "#107e31";
}
function dot(index) {
images.forEach(function (image) {
image.classList.remove("active");
});
document.getElementById("content" + index).classList.add("active");
i = index - 1;
indicator(index);
}
// FAQ JS
let toggles = document.getElementsByClassName('toggle');
let contentDiv = document.getElementsByClassName('content');
let icons = document.getElementsByClassName('icon');
for(let i=0; i<toggles.length; i++){
toggles[i].addEventListener('click', ()=>{
if( parseInt(contentDiv[i].style.height) != contentDiv[i].scrollHeight){
contentDiv[i].style.height = contentDiv[i].scrollHeight + "px";
toggles[i].style.color = "#0084e9";
icons[i].classList.remove('fa-plus');
icons[i].classList.add('fa-minus');
}
else{
contentDiv[i].style.height = "0px";
toggles[i].style.color = "#111130";
icons[i].classList.remove('fa-minus');
icons[i].classList.add('fa-plus');
}
for(let j=0; j<contentDiv.length; j++){
if(j!==i){
contentDiv[j].style.height = "0px";
toggles[j].style.color = "#111130";
icons[j].classList.remove('fa-minus');
icons[j].classList.add('fa-plus');
}
}
});
}
When using $() with selectors, it's very similar to document.querySelectorAll().
So, if you wanted to query for a specific ID, you'd need to use a pound symbol # in front of the ID:
$('#some-id')
Really though, there's no reason I can think of these days to use jQuery. Additionally, you could probably remove the need for any of this JavaScript by simply using anchor fragments/hash and the :target selector. Your URLs could be like somepage.html#slide-1.

Javascript- Dynamic variable loop

I'm trying to reduce the amount of code I repeat.
Currently I have the below:
var item1H = $(".item-1").height();
var item1W = $(".item-1").height();
$(".item-1 .text").css('margin-left', -item1W/2);
$(".item-1 .text").css('margin-bottom', -item1H/2);
var item2H = $(".item-2").height();
var item2W = $(".item-2").height();
$(".item-2 .text").css('margin-left', -item2W/2);
$(".item-2 .text").css('margin-bottom', -item2H/2);
I'm looking to put this into a for loop where the variable number would count up to whatever number I needed it to stop.
You can make function like this and use whenever you want
toSetMargin(".item-2")
toSetMargin(".item-2")
function toSetMargin(objStr){
var widthTmp = $(objStr + ' .text').height();
var heightTmp = $(objStr + ' .text').height();
obj.css('margin-left', -widthTmp/2);
obj.css('margin-bottom', -heightTmp/2)
}
This code not impact any other code.
You could use $('[class^="item-"]') to get all the elements that have a class that starts with item-, and the loop over them
$('[class^="item-"]').each(function(){
var $elem = $(this);
var item1H = $elem.height();
var item1W = $elem.width();
$elem.find('.text').css({'margin-left': -item1W/2,'margin-bottom':-item1H/2});
});
Ooh boy, one of these problems. This should help (untested):
for(i=1;i<=STOPPING_NUMBER;i++){
window["item"+i+"H"] = $(".item-"+i).height();
window["item"+i+"W"] = $(".item-"+i).width(); //Was height, accident?
$(".item-"+i+" .text").css('margin-left', 0-window["item"+i+"W"]/2); //Hope this works lol
$(".item-"+i+" .text").css('margin-bottom', 0-window["item"+i+"H"]/2);
}
Guessing these lines:
var item1W = $(".item-1").height();
var item2W = $(".item-2").height();
Should have been:
var item1W = $(".item-1").width();
var item2W = $(".item-2").width();
You could do something like:
function setCSS(item,attr,val) {
$(item +" .text").css(attr, (val * -1)/2);
}
var i, max = 10;
for(i=1;i<=max;i++) {
setCSS(".item-"+ i,"margin-left",$(".item-"+ i).width());
setCSS(".item-"+ i,"margin-bottom",$(".item-"+ i).height());
}
Or something less flexible within the function:
function setCSS(item,w,h) {
$(item +" .text").css("margin-left", (w * -1)/2);
$(item +" .text").css("margin-bottom", (h * -1)/2);
}
var i, max = 10;
for(i=1;i<=max;i++) {
setCSS(".item-"+ i,$(".item-"+ i).width()),$(".item-"+ i).height());
}
Something like this should be pretty acceptible in your case, I guess:
for (var i = 1, len = someN; i < len; i++) {
var $item = $('.item-' + i);
$item.find('.text').css({
'margin-left': -$item.width() / 2,
'margin-bottom': -$item.height() / 2
});
}

while loop in jQuery

i need to use while loop, i wonder if there are any syntax changes in jQuery
in javascript
var text = "";
var i = 0;
while (i < 10) {
text += "<br>The number is " + i;
i++;
}
document.getElementById("demo").innerHTML = text;
how can i perform loop in jquery just like this?
There is no difference between javascript and jquery in case of while loop
$(function () {
var text = "";
var i = 0;
while (i < 10) {
text += "<br>The number is " + i;
i++;
}
$("#demo").html(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="demo"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javescript">
$(document).ready(function () {
var text = "";
var i = 0;
while (i < 10) {
text += "<br>The number is " + i;
i++;
}});
</script>
It would be the same in jQuery. Here is the documentation.
There is a popular loop method in jQuery, but it doesn't apply to your example. $.each() allows you to loop through arrays and array-like objects.
There is no difference in javascript and jquery while loops.
$(document).ready(function () {
var text = "";
var i = 0;
while (i < 10) {
text += "<br>The number is " + i;
i++;
}});
This will work.

Javascript function not recognizing id in getElementById

I am adding a row to a table, and attached an ondblclick event to the cells. The function addrow is working fine, and the dblclick is taking me to seltogg, with the correct parameters. However, the var selbutton = document.getElementById in seltogg is returning a null. When I call seltogg with a dblclick on the original table in the document, it runs fine. All the parameters "selna" have alphabetic values, with no spaces, special characters, etc. Can someone tell me why seltogg is unable to correctly perform the document.getElementById when I pass the id from addrow; also how to fix the problem.
function addrow(jtop, sel4list, ron4list) {
var tablex = document.getElementById('thetable');
var initcount = document.getElementById('numrows').value;
var sel4arr = sel4list.split(",");
var idcount = parseInt(initcount) + 1;
var rowx = tablex.insertRow(1);
var jtop1 = jtop - 1;
for (j = 0; j <= jtop1; j++) {
var cellx = rowx.insertCell(j);
cellx.style.border = "1px solid blue";
var inputx = document.createElement("input");
inputx.type = "text";
inputx.ondblclick = (function() {
var curj = j;
var selna = sel4arr[curj + 2];
var cellj = parseInt(curj) + 3;
inputx.id = "cell_" + idcount + "_" + cellj;
var b = "cell_" + idcount + "_" + cellj;
return function() {
seltogg(selna, b);
}
})();
cellx.appendChild(inputx);
} //end j loop
var rowCount = tablex.rows.length;
document.getElementById('numrows').value = rowCount - 1; //dont count header
} //end function addrow
function seltogg(selna, cellid) {
if (selna == "none") {
return;
}
document.getElementById('x').value = cellid; //setting up for the next function
var selbutton = document.getElementById(selna); //*****this is returning null
if (selbutton.style.display != 'none') { //if it's on
selbutton.style.display = 'none';
} //turn it off
else { //if it's off
selbutton.style.display = '';
} //turn it on
} //end of function seltogg
You try, writing this sentence:
document.getElementById("numrows").value on document.getElementById('numrows').value
This is my part the my code:
contapara=(parseInt(contapara)+1);
document.getElementById("sorpara").innerHTML+="<li id=\"inputp"+contapara+"_id\" class=\"ui-state-default\"><span class=\"ui-icon ui-icon-arrowthick-2-n-s\"></span>"+$('#inputp'+contapara+'_id').val()+"</li>";
Look you have to use this " y not '.
TRY!!!!

jQuery: Initial data for rating

I have found a pretty stuff for rating entries: http://www.fyneworks.com/jquery/star-rating/. It's good and easy. But I still need some more.
My code:
<div data-rating="4/5" class="entry"></div>
Desired function:
function init_rating(rate) { //... }
$(".entry").html( init_rating($(this).attr("data-rating")) );
Thanks much,
Here:
function init_rating(selector) {
var entry = $(selector);
var output = "";
var input = "<input name=\"star\" type=\"radio\" class=\"star\""
var checked = " checked=\"checked\"";
var close = "/>";
var params = entry.attr("data-rating").split("/", 2);
var rating = parseInt(params[0]);
var total = parseInt(params[1]);
for (var i = 0; i < total; i++) {
output += input;
if (i == rating - 1) output += checked;
output += close;
}
entry.html(output);
$('input[type=radio].star').rating();
}
init_rating(".entry");
fiddle: http://jsfiddle.net/qcxvW/20/

Categories

Resources