How do i switch Javascript to Jquery code? - javascript

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.

Related

Reset data from document getElementById

I can't reset an element in my code.
I have a code that allows me to create spans with each click. However, each click creates additional spans without overwriting the previous ones. I would like this one not to keep the previous spans in value.
This my code :
const fieldText = document.getElementById('fieldDashboardText');
if(info.title != undefined){
isFields = true;
isFirst = true;
const title = info.title;
fieldText.innerHTML = fieldText.innerHTML + '<a class="fiedsInVerbatimDashboard"> Title : </a>' + '<br>';
let newTitle = title.replace(/[,.:;!?()"]+/g, '');
newTitle = newTitle.replace(/[']+/g, ' ');
const features = newTitle.split(' ');
const positiveValues = app.generateLimeOpacity(positive, 'positive');
const negativeValues = app.generateLimeOpacity(negative, 'negative');
const newDataLime = [...positiveValues, ...negativeValues];
var spanCounter = 0;
console.log("Features in tile : ", features);
for (let i = 0; i < features.length; i++) {
for (let j = 0; j < newDataLime.length; j++) {
if (features[i] === newDataLime[j].label) {
spanCounter ++
// Max 12 span by each line for ver
if(spanCounter == 12){
spanCounter = 0;
}
features[i] = `<span class="verbatim-dashboard__text__lime hide" style="background-color: ${newDataLime[j].rgba};">${features[i]}</span>`;
}
}
}
fieldText.innerHTML = fieldText.innerHTML + features.join(" ");
fieldText.innerHTML = fieldText.innerHTML + '<br>';
}
I would like every click to have the fieldText constant "empty" like the first call of some sort. I hope I have been clear enough.
Thank you in advance!
Change
fieldText.innerHTML = fieldText.innerHTML + features.join(" ");
to
fieldText.innerHTML = features.join(" ");
You are adding features to previous innerHTML. You set innerHTML to features not concat with existing innerHTML.
fieldText.innerHTML = features.join(" ") + '<br>';

Toggling background color of div

Title, my only problem is that when I've created all elements on my page, and clicked all of them, my page looks like a chess board.
I can only "toggle" the background color of half too. So it's not only that they don't change color on the first click, they don't change at all.
This is my Javascript:
for (var i = 0; i < 10; i++) {
var itemContainer = document.createElement("div" + i);
itemContainer.id = "div" + i;
itemContainer.className = "item";
itemContainer.innerHTML = "Hello!";
for (let i = 0; i < 10; i++) {
$('div' + i).click(function() {
if (this.className == "item") {
this.className = "itemselected";
} else {
this.className = "item";
}
});
}
document.getElementById("page").appendChild(itemContainer);
}
I made a JSFiddle for you who want it.
I've seen a few other questions about how to toggle the color of backgrounds, but none of them have the same problem as me.
You inserted your second loop into the first one, every second i got skipped. And probably was able to change your divs up to i=18
JSFiddle
for (var i = 0; i < 10; i++) {
var itemContainer = document.createElement("div" + i);
itemContainer.id = "div" + i;
itemContainer.className = "item";
itemContainer.innerHTML = "Hello!";
document.getElementById("page").appendChild(itemContainer);
}
for (let i = 0; i < 10; i++) {
$('div' + i).click(function() {
if (this.className == "item") {
this.className = "itemselected";
} else {
this.className = "item";
}
});
}
Edit: You could simply put the content of your second loop into the first loop, to simplify your code a bit.
You don't need 2 loops try that
for (var i = 0; i < 10; i++) {
var itemContainer = document.createElement("div");
itemContainer.id = "div" + i;
itemContainer.className = "item";
itemContainer.innerHTML = "Hello!";
document.getElementById("page").appendChild(itemContainer);
$('#div' + i).click(function() {
alert("here");
if (this.className == "item") {
this.className = "itemselected";
} else {
this.className = "item";
}
});
}
fiddle example
You were close, missing "#" of id element
$('div' + i).click(function() {
$('#div' + i).click(function() {
and you have inserted the second loop inside first one
https://jsfiddle.net/snbtchph/
Your selector at line 8 of your JavaScript is missing the # so the jQuery is looking for <div0>, <div1>, <div2>..., and, your line 2 of JavaScript is var itemContainer = document.createElement("div" + i); which actual creating elements div0, div1....
And since you are using jQuery , I have also revised some code to use it instead of native JavaScript: https://jsfiddle.net/xfr496p6/5/
I have also added css .item { display: inline-block; } to makes the elements placed in a row.
There are a few problems with your code:
var itemContainer = document.createElement("div" + i);
Creating non-existant elements like <div1> is impossible, remove the iterator.
for (let i = 0; i < 10; i++) {
jQuery's .click() doesn't need a for loop, but adds the event listener to every case, this is not needed.
document.getElementById("page").appendChild(itemContainer);
Apply this directly in after the .innerHTML
In addition, you seem to randomly use ES6, jQuery, and VanillaJS through your entire codebase, I'd like to advise you to be consistant with how you write your applications.
I've updated your fiddle with the working changes.
https://jsfiddle.net/xfr496p6/8/
Updated javascript:
for (var i = 0; i < 10; i++) {
var itemContainer = document.createElement("div");
itemContainer.id = "div" + i;
itemContainer.className = "item";
itemContainer.innerHTML = "Hello!" + i;
document.getElementById("page").appendChild(itemContainer);
}
$('div').click(function() {
if (this.className == "item") {
this.className = "itemselected";
} else {
this.className = "item";
}
});
Why do you have 2 nested loops?
try this
for (var i = 0; i < 10; i++) {
var itemContainer = document.createElement("div" + i);
itemContainer.id = "div" + i;
itemContainer.className = "item";
itemContainer.innerHTML = "Hello!";
document.getElementById("page").appendChild(itemContainer);
}
for (let i = 0; i < 10; i++) {
$('div' + i).click(function() {
if (this.className == "item") {
this.className = "itemselected";
} else {
this.className = "item";
}
});
}
JSFIDDLE
for (var i = 0; i < 10; i++) {
var itemContainer = document.createElement("div" + i);
itemContainer.id = "div" + i;
itemContainer.className = "item";
itemContainer.innerHTML = "Hello!";
$(itemContainer).click(function() {
if (this.className == "item") {
this.className = "itemselected";
} else {
this.className = "item";
}
});
document.getElementById("page").appendChild(itemContainer);
}

Font Size changes according to count of word

function test(data) {
wordCount = {};
theWords = [];
allWords = data.match(/\b\w+\b/g); //get all words in the document
for (var i = 0; i < allWords.length; i = i + 1) {
allWords[i] = allWords[i].toLowerCase();
var word = allWords[i];
if (word.length > 5) {
if (wordCount[word]) {
wordCount[word] = wordCount[word] + 1;
} else {
wordCount[word] = 1;
}
}
}
var theWords = Object.keys(wordCount); // all words over 5 characters
var result = "";
for (var i = 0; i < theWords.length; i = i + 1) {
result = result + " " + theWords[i];
$("theWords.eq[i]").css("fontSize", (wordCount.length + 50) + 'px');
}
return result;
}
console.log(test("MyWords"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I'm having troubles with the syntax of the line "$("theWords[i]......."
I realize how simple of a question this is, and not academic to the community, but I have been fumbling with this syntax for awhile and can't find any specific forum to correct my syntax error.
I am attempting to have the font size change according to the amount of times the word appears in a document.
wordCount = count of appears.
theWords = all words I would like to have the rule applied to
I manage to have something working with what you did using a bit more of jQuery to build the list of words to show. hope it helps :D.
$(document).ready(function() {
var data = $(".sometext").text();
wordCount = {}; theWords = []; allWords = data.match(/\b\w+\b/g); //get all words in the document
for (var i = 0; i < allWords.length; i++){
allWords[i] = allWords[i].toLowerCase();
var word = allWords[i];
if (word.length > 5) {
if (wordCount[word]) {
wordCount[word] = wordCount[word] + 1;
} else {
wordCount[word] = 1;
}
}
}
var theWords = Object.keys(wordCount); // all words over 5 characters
for(var i = 0; i < theWords.length; i = i + 1) {
$('<span/>', {
'text': theWords[i] + " ",
'class': theWords[i]
}).appendTo('.result');
}
for(var i = 0; i < theWords.length; i++) {
$("." + theWords[i]).css("font-size", 15 + wordCount[theWords[i]]*5 + "px");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="sometext">javascript is a language that could be a language without such things as language but not without things as parenthesis. language is the bigest word here.</p>
<hr>
<div class="result"></div>

Regular expression to remove all the that is coming before and after <div> tag

I have seen references in this site. But I have this problem that is particular to my code.
I have some variable like
viewSourceText = "koushik ↵<div id="okokoko">some value </div> "
now i want to remove "&nbsp" appearing before and after the tag.So that output would be like this:
viewSourceText = "koushik<div id="okokoko">some value </div>"
now my code sample is:
viewSourceText.replace(/ \n<div/g, "<div>");
viewSourceText.replace(/</div> /g, "</div>");
But not working properly.
Here the proper way to do it in the DOM without regular expressions:
function removeNbspAroundDivs (start) {
var divs = start.getElementsByTagName("div");
for (var i = 0, len = divs.length; i < len; i++) {
var div = divs[i];
var element = div;
while ((element = element.previousSibling) && element.nodeType == 3) {
element.nodeValue = element.nodeValue.replace(/[\u00A0\n]+$/, "");
if (element.nodeValue.length > 0) break;
}
var element = div;
while ((element = element.nextSibling) && element.nodeType == 3) {
element.nodeValue = element.nodeValue.replace(/^[\u00A0\n]+/, "");
if (element.nodeValue.length > 0) break;
}
}
};
Fiddle

Javascript/ActionScript do for each indexOf?

The screenshot below the code shows me issue. It only rainbowfies one instance of text.
How can I get this code to do each [rainbow]specified[/rainbow] text?
It's actually for ActionScript but it works in Javascript too so I've been testing on http://jsfiddle.net
var txt = "This is a [rainbow]test to show that I can[/rainbow] make whatever I want [rainbow]appear as a rainbow[/rainbow] because I am [rainbow]awesome[/rainbow].";
if ((txt.indexOf("[rainbow]") > -1) && (txt.indexOf("[/rainbow]") > -1)) {
var firstChar = txt.indexOf("[rainbow]") + 9;
var lastChar = txt.indexOf("[/rainbow]");
var RAINBOWTEXT = '';
var i = firstChar;
while (i < lastChar) {
RAINBOWTEXT += txt.charAt(i);
i++
}
var text = RAINBOWTEXT;
var texty = '';
colors = new Array('ff00ff', 'ff00cc', 'ff0099', 'ff0066', 'ff0033', 'ff0000', 'ff3300', 'ff6600', 'ff9900', 'ffcc00', 'ffff00', 'ccff00', '99ff00', '66ff00', '33ff00', '00ff00', '00ff33', '00ff66', '00ff99', '00ffcc', '00ffff', '00ccff', '0099ff', '0066ff', '0033ff', '0000ff', '3300ff', '6600ff', '9900ff', 'cc00ff');
var i = 0;
while (i <= text.length) {
var t = text.charAt(i);
if (t != undefined) {
texty += "<font color=\"#" + colors[i % colors.length] + "\">" + t + "</font>";
i++;
}
}
texty = texty.replace("> <", "> <");
var REPLACEME = "[rainbow]" + RAINBOWTEXT + "[/rainbow]";
txt = txt.replace(REPLACEME, texty);
document.write(txt);
}​
If we can make assumptions about no interleaving or nesting of [rainbow] tags, I'd just use a regular expression with a simple replacer callback:
var rainbowified = txt.replace(/\[rainbow\](.*?)\[\/rainbow\]/, function(textWithTags, textBetweenTheseTags) {
var text = textBetweenTheseTags;
....
for(var i = 0; i < text.length; ++i) {
// rainbowify each letter of text...
}
...
return textWithFontTags;
}
You can use this to get a new string with the transformation you want.
Also, the font tag is depricated; you should use span with color:#XXXXXX in the style attribute.
var colors = [
'f0f', 'f0c', 'f09', 'f06', 'f03', 'f00', 'f30', 'f60', 'f90', 'fc0',
'ff0', 'cf0', '9f0', '6f0', '3f0', '0f0', '0f3', '0f6', '0f9', '0fc',
'0ff', '0cf', '09f', '06f', '03f', '00f', '30f', '60f', '90f', 'c0f'
];
function rainbowify(text) {
return text.replace(/\[rainbow\](.*)\[\/rainbow\]/g, function(_, inner){
return inner.replace(/./g, function(ch, i){
return '<span style="color:#' + colors[i % colors.length] + ';">' + ch + '</span>';
});
})
}
Here's how I'd do it.
Make it a loop. .indexOf can take a starting point as the second parameter, so with starting the next iteration at lastChar+10 should work.
Apart from that, it might be easier to do it fully with regex and .replace:
return txt.replace(/\[rainbow\](.+?)\[\/rainbow\]/g, function(all, match, index, str) {
return createRGBrainbowArray(match.length).map(function(color, i) {
return '<span style="color:#'+color+'">'+match[i]+'</span>';
}).join("");
});
function createRGBrainbowArray(l) {
// should return an Array of length l with hexadecimal color strings,
// representing a nice rainbow
}

Categories

Resources