JS add +10 then sort DIV - javascript

GOAL script returns 20,13,12,11
Hi I am trying to make these two operations into a single operation on Load.
when loaded the page returns 3,2,10,1
so I have added a button to trigger a +10 function.
which returns 13,12,20,11
Both these functions work independently, however i need the the entire thing to work together so that it returns 20,13,12,11 on load
I don't want any buttons>>>>
<script src="js/jquery-1.4.1.min.js"></script>
<!--CSS-->
<style type="text/css">
.box {
border: 1px solid #000;
padding: 2px;
margin: 2px;
}
</style>
<!--JAVASCRIPT-->
<!-- (A) ADDS +10 to div No-->
<script type='text/javascript'>
$(document).ready(function(){
$("#increase").click(function(event){
$("div.box").each(function(idx,elem){
$(this).text( parseInt($(this).text(),10) +10 );
});
return false;
});
});
</script>
<div id="containerSort">
<!-- (B) SORTS div -->
<script type='text/javascript'>
$(function(){
var $divs = $("div.box");
$( "#numBnt" ).one("load", function() {
console.log('loaded')
var numericallyOrderedDivs = $divs.sort(function (a, b) {
return $(a).find("h7").text() < $(b).find("h7").text();
});
$("#containerSort").html(numericallyOrderedDivs);
});
});
</script>
<!--HTML-->
<div class="box"><h7>1</h7></div>
<div class="box"><h7>2</h7></div>
<div class="box"><h7>3</h7></div>
<div class="box"><h7>10</h7></div>
<img src="http://myscot.com/ImagesMain/myscotLogoResp120.jpg" id="numBnt"/>
</div>
<button id="increase">+10</button>
window.addEventListener("load", function(){...}) how would I combine the 2 functions to the event listener?

There are 2 ways to solve your problem
Call button's click event on page load.
Create a function which will wrap everything and assign it as eventListener.
Note:
$(function(){}) is a short hand for $(document).ready() and its a bad practice to have multiple document.ready functions.
H7 is not a valid header tag as mentioned by #Niet the Dark Absol. Browser might consider it as a custom element and process similar to span tag. (This is just a guess).
Below code:
$("div.box").each(function(idx, elem) {
$(this).text(parseInt($(this).text(), 10) + 10);
});
this will make multiple DOM operation. Its bad practice to manipulate DOM in a loop.
Following is a sample code. Also I have updated your code a bit.
JSFiddle.
$(document).ready(function() {
$("#increase").trigger("click");
});
$("#increase").click(function() {
var valArr = getValues();
valArr = addNumber(valArr);
valArr = sortValues(valArr);
createAndRenderHTML(valArr, "#containerSort");
});
function getValues() {
var returnArray = [];
$("div.box").each(function(id, el) {
returnArray.push(parseInt($(el).text(), 10));
});
return returnArray;
}
function addNumber(arr) {
return arr.map(function(item) {
return parseInt(item, 10) + 10;
});
}
function sortValues(arr) {
return arr.sort(function(a, b) {
return a > b ? -1 : a < b ? 1 : 0
});
}
function createAndRenderHTML(arr, el) {
var _html = arr.map(function(item) {
return "<div class='box'> <h7>" + item + "</h7></div>"
}).join("");
$(el).html(_html);
}
.box {
border: 1px solid #000;
padding: 2px;
margin: 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<div id="containerSort">
<!--HTML-->
<div class="box">
<h7>1</h7>
</div>
<div class="box">
<h7>2</h7>
</div>
<div class="box">
<h7>3</h7>
</div>
<div class="box">
<h7>10</h7>
</div>
<img src="http://myscot.com/ImagesMain/myscotLogoResp120.jpg" id="numBnt" />
</div>
<button id="increase">+10</button>

Related

Giving a div a style on click

applying a class to an element only when clicked
You could make 2 different click functions. One for trap and one for the rest.
For that you need to know which ones are the other ( safe ones ). See otherDivsIds in the below code. You find the other id's using the filter function in the idArray and then loop through them ( with forEach or something else ) and add event listeners to each of them.
I would also suggest to ' swap ' the naming of the variables trapBox and trapId. Vice versa would be better
See code below
var idArray = ['one','two','three','four'];
var trapBox = idArray[Math.floor(Math.random() * idArray.length)];
var trapId= document.getElementById(trapBox);
trapId.addEventListener('click', boomClickFunction, false);
var otherDivsIds = idArray.filter(id => id !== trapBox);
otherDivsIds.forEach(id => {
safeBox = document.getElementById(id);
safeBox.addEventListener('click', safeClickFunction, false)
})
var timeoutId = window.setTimeout(ticker, 5000);
function ticker() {
document.getElementById('timesUp').innerHTML = "Time's up!";
document.body.style.backgroundColor = "black";
}
function boomClickFunction() {
this.classList.add('boom')
}
function safeClickFunction() {
this.classList.add('safe')
}
div {
width: 20px;
height: 20px;
background-color: green;
margin: 20px;
float: left;
}
.boom {
background-color: red;
}
.safe {
background-color: lightblue;
}
#timesUp {
color: white;
}
<div id='one'>
</div>
<div id='two'>
</div>
<div id='three'>
</div>
<div id='four'>
</div>
<span id="timesUp">
</span>
You can add a class to an element by using classList.add('classToBeAdded').
In your case, you could put it in your clickFunction:
trapId.classList.add('boom');

Method fired multiple times on click event

I'm building a web app in which the user can type in any key word or statement and get in return twenty results from wikipedia using the wikipedia API. AJAX works just fine. When the web app pulls data from wikipedia it should display each result in a DIV created dynamically.
What happens is that, when the click event is fired, the twenty DIVs are created five times, so one hundred in total. I don't know why but, as you can see in the snippet below, the web app creates twenty DIVs for each DOM element that has been hidden (through .hide) when the click event is fired.
Here's is the code:
function main() {
function positive() {
var bar = document.getElementById("sb").childNodes[1];
var value = bar.value;
if (!value) {
window.alert("Type in anything to start the research");
} else {
var ex = /\s+/g;
var space_count = value.match(ex);
if (space_count == null) {
var new_text = value;
} else {
new_text = value.replace(ex, "%20");
//console.log(new_text);
}
url = "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=&list=search&continue=-%7C%7C&srsearch=" + new_text + "&srlimit=20&sroffset=20&srprop=snippet&origin=*";
var request = new XMLHttpRequest();
request.open("GET", url);
//request.setRequestHeader("Api-User-Agent", "Example/1.0");
request.onload = function() {
var data = JSON.parse(request.responseText);
render(data);
//console.log(data);
}
request.send();
}
}
function render(data) {
$("#first_h1, #first_h3, #sb label, #second_h1, #second_h3").hide("slow", function() {
$("#sb input").css({
"float":"left",
"margin-left":"130px"
});
$("#first_btn").css({
"float":"left"
});
var title = data.query.search[0].title;
var new_text = document.createTextNode(title);
var new_window = document.createElement("div");
new_window.appendChild(new_text);
new_window.setAttribute("class", "window");
var position = document.getElementsByTagName("body")[0];
position.appendChild(new_window);
//}
});
}
var first_btn = document.getElementById("first_btn");
first_btn.addEventListener("click", positive, false);
}
$(document).ready(main);
html {
font-size: 16px;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;รน
}
.align {
text-align: center;
}
#first_h1 {
margin-top: 30px;
}
#first_h3 {
margin-bottom: 30px;
}
#sb {
margin-bottom: 10px;
}
#second_h1 {
margin-top: 30px;
}
#second_h3 {
margin-bottom: 30px;
}
.window {
width: 70%;
height: 150px;
border: 3px solid black;
margin: 0 auto;
margin-top: 20px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Wikipedia Viewer</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="css/main.css">
</head>
<body>
<h1 class="align" id="first_h1">Wikipedia Viewer</h1>
<h3 class="align" id="first_h3">Type in a key word about the topic you are after<br>and see what Wkipedia has for you..</h3>
<p class="align" id="sb">
<input type="text" name="search_box" placeholder="Write here">
<label for="search_box">Your search starts here...</label>
</p>
<p class="align" id="first_btn">
<input type="submit" value="SEND">
</p>
<h1 class="align" id="second_h1">...Or...</h1>
<h3 class="align" id="second_h3">If you just feel eager of random knowledge,<br>punch the button below and see what's next for you...</h3>
<p class="align" id="second_btn">
<input type="submit" value="Enjoy!">
</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
window.jQuery || document.write('<script src="js/jquery-3.2.1.min.js"><\/script>')
</script>
<script type="text/javascript" src="js/script.js"></script>
</body>
</html>
I made the code easier to read by erasing the for loop. As you can see, even with just one result, it is displayed five times.
Do you know guys why it happens?
thanks
The line:
$("#first_h1, #first_h3, #sb label, #second_h1, #second_h3").hide("slow", function() {})
Says, for every element in this "list", hide the element and run this block of code after hidden.
This code is the culprit:
$("#first_h1, #first_h3, #sb label, #second_h1, #second_h3").hide("slow",
function() {...});
The callback function is called five times, one for each ID listed, not once for all of them, as you might expect.
A workaround is to create a class (say, "hideme"), apply it to each element you want to hide, and write:
$('.hideme').hide("slow", function() {...});
function render(data) {
$("#first_h1, #first_h3, #sb label, #second_h1, #second_h3").hide("slow", function() {
$("#sb input").css({
"float":"left",
"margin-left":"130px"
});
$("#first_btn").css({
"float":"left"
});
}); // Finish it here..
var title = data.query.search[0].title;
var new_text = document.createTextNode(title);
var new_window = document.createElement("div");
new_window.appendChild(new_text);
new_window.setAttribute("class", "window");
var position = document.getElementsByTagName("body")[0];
position.appendChild(new_window);
//}
// }); Move this line..
}
As described in the docs:
complete: A function to call once the animation is complete, called once per matched element.
Which means this line will call the handle function 5 times with 5 matched elements.
$("#first_h1, #first_h3, #sb label, #second_h1, #second_h3").hide("slow", function() {
The easiest solution is moving the render codes outside of the hide event handler

How to remove attribute found within a variable?

I have
var $imageSelected = '<div style="position: absolute"><span>hello</span></div>';
I need to remove the style attribute form the created variable
I tried:
$imageSelected + "*").removeAttr("style");
and
$imageSelected).find("*").removeAttr("style");
Full code with added replace functionality as per first answer:
$(".grid-item").on("click", function() {
var $imageSelected = $(this).prop('outerHTML');
var $paste = $imageSelected.replace(/style.+"/, '');
$('#usp-custom-4').val(function(_, currentValue) {
return currentValue + $paste
});
});
Using $imageSelected).removeAttr("style"); doesn't work and by using the code above it does remove style yet it is pasting many times the code into the text area, not this clicked only
$('#usp-custom-4') is the textarea id
Clone, remove attr, select the html
$(".grid-item").on("click", function() {
var $imageSelected = $(this).clone().removeAttr("style"),
code = $("<div></div>").append($imageSelected).html();
//code = $imageSelected.prop('outerHTML');
$('#usp-custom-4').val(function(_, currentValue) {
return currentValue + code
});
});
div {
padding: 1em; border: 1px solid black; margin: .5em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="grid-item" style="display:block;">1</div>
<div class="grid-item" style="display:block;">2</div>
<div class="grid-item" style="display:block;">3</div>
<div class="grid-item" style="display:block;">4</div>
<textarea id="usp-custom-4"></textarea>
You can use e.g. replace function.
var $myValue = '<div style="position: absolute"><span>hello</span></div>';
$myValue = $myValue.replace(/ style.+"/, '');
console.log($myValue);

Custom html tab implementation problems

my use case : create tab like experience. clicking on add button creates a (horz tab button) and a corresponding div, which is linked via onclick listener, dynamically.
problems :
on clicking add button, values from previous tabs are reset (which is obvious wrt to the way $tabs_prev & $menu_prev is populated) and
their respective js goes away (which I can't understand, why?)
a remove tab implementation (because the way I've coded these tabs, removing a tab and corresponding div isn't really simple, so, any clues in this direction, maybe?)
code : fiddle : http://jsfiddle.net/g58fzs75/1/
HTML:
<body>
<input id="hidden" type="hidden" value="1"></input>
<div id="template_tabBtn" style="display:none">
<input type="button" value="add" onclick="addTab()"></input>
</div>
<ul id="menu">
</ul>
<div id="tabs">
</div>
<div id="template_tabBar" style="display:none">
<li>
<input type="button" id="tab_btn" class="template_tabBar" value="Tab" onclick="tabClick(this)"></input>
</li>
</div>
<div id="template_tabs" style="display:none">
<div id="tabs" class="template_tabs tab_div" value="1">
<input type="text" id="txt" class="template_tabs" value="alert"></input>
<input type="button" id="btn" class="template_tabs" value="alert"></input>
</div>
</div>
</body>
CSS:
<style>
ul#menu {
padding: 0;
}
ul#menu li {
display: inline;
}
ul#menu li input {
background-color: black;
color: white;
padding: 10px 20px;
text-decoration: none;
border-radius: 4px 4px 0 0;
}
ul#menu li input:hover {
background-color: orange;
}
</style>
jQuery :
<script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
<script>
$tabs_prev = "";
$menu_prev = "";
$add_btn = "";
$current_tabID = "";
function tabClick(id) {
showCurrent($(id).attr('id'));
}
function addTab() {
var tabCount = parseInt($('#hidden').val()) + 1;
$('#hidden').val(tabCount);
run(tabCount);
showCurrent($('#tabs-' + tabCount).attr('id'));
}
$(document).ready(function() {
$add_btn = "<li>" + $('#template_tabBtn').html() + "</li>";
run(1);
});
function run(tabCount) {
//$tabs_prev += main($('#template_tabs'),tabCount);//alert("tabs\n"+$tabs_prev);
$menu_prev += main($('#template_tabBar'), tabCount); //alert("menu\n"+$menu_prev);
$('#tabs').html($('#tabs').html() + main($('#template_tabs'), tabCount));
$('#menu').html($menu_prev + $add_btn);
logic(tabCount);
}
function main(target, tabCount) {
$htmlBackup = $(target).html();
$('.' + $(target).attr('id')).each(function() {
$(this).attr('id', $(this).attr('id') + "-" + tabCount).removeClass($(target).attr('id'));
$(this).attr('value', $(this).attr('value') + "-" + tabCount);
});
$html = $(target).html();
$(target).html($htmlBackup);
return $html;
}
function logic(tabCount) {
$('#btn-' + tabCount).click(function() {
alert($('#txt-' + tabCount).val());
});
}
function showCurrent(current_id) {
$('.tab_div').each(function() {
var id = $(this).attr('id');
var id_num = id.substr(id.lastIndexOf('-') + 1, id.length);
var current_id_num = current_id.substr(current_id.lastIndexOf('-') + 1, current_id.length);
if (id_num == current_id_num) {
$("#tabs-" + id_num).show();
$('#tab_btn-' + id_num).css({
"background-color": "orange"
});
} else {
$("#tabs-" + id_num).hide();
$('#tab_btn-' + id_num).css({
"background-color": "black"
});
}
});
}
</script>
The reason why your javascript is disappearing is because resetting the innerHTML deletes the onclick handlers on the elements. Why: the original elements are destroyed, including references to events and new elements are created.
The code responsible for this:
$('#tabs').html($('#tabs').html() + main($('#template_tabs'), tabCount));
Please use jQuery's appending of an element by cloning the template tab:
$('#tabs').append($('#template_tabs').clone(true));
Append appends htmlstrings or elements to an parent element. It's a buffed up version of the documents native 'appendChild'.
clone clone the template element (makes a copy). You can do this in your function main and return it to the append function.
function main(tabCount)
{
var node = $('#template_tabs').clone(true));
//do things with the node, like setting an onclick handler, or id.
//example
node.setAttribute("id", "tab" + tabCount);
}
Removing can be done also:
function removeNode(node)
{
//provide a node via jQuery
//example: removeNode($("#tab2")) <-- now tab2 will be removed from the DOM.
node.remove();
}

I would need two functions to be executed onclick

The two functions when a user clicks the next button will call the next() and fbsharing() function.
next swaps between 4 divs that will display only one at a time (WORKING)
fbsharing (will display a customised share button in a div id=fbshare (FAIL)
here is my jsfiddle : http://jsfiddle.net/U3jdm/
<div id="content" style="width:60%; float:left; padding: 10px 10px 10px 10px;">
<div id="ncholder">
<div id="ncframe"></div>
<div class="PortSwap" id="swap0">
111111111111
</div>
<div class="PortSwap" id="swap1">
2222222222
</div>
<div class="PortSwap" id="swap2">
333333333
</div>
<div class="PortSwap" id="swap3">
4444444444
</div>
</div>
<div id="ncnav" style="width:83%; float:left; padding: 30px 10px 10px 10px;">
<div style="width:30%; float:right; color:#66ce9d; font-size:18px; font-weight:bold;">
<div style="width:30px; height:30px; float:left;"><img src="leftnav.png" alt="Previous" onClick="(function(){prev(); fbSharing();})();"/></div>
<div style="width:30px; height:30px; float:right;"><img src="rightnav.png" alt="Next" onClick="(function(){next(); fbSharing();})();"/></div>
</div></div>
<div id="fbshare" style="color:#ed1a64; font-size:18px; font-weight:bold;"> </div>
</div>
<script>
$(function () {
"use strict";
$('.PortSwap').hide().eq(0).addClass('active').show();
});
function prev() {
var current = $('.PortSwap.active'),
prev = current.prev('.PortSwap');
console.log(prev.length, prev);
if (prev.length) {
current.hide().removeClass('active');
prev.addClass('active').show();
}
}
function next() {
var current = $('.PortSwap.active'),
next = current.next('.PortSwap');
if (next.length) {
current.hide().removeClass('active');
next.addClass('active').show();
}
}
function fbSharing() {
var test = document.getElementByClassName("PortSwap active");
var share;
var testid = test.id;
if (testid = 'swap0') {
share ="1111111";
}
else if (test.ID = 'swap1') {
share ="2222";
}
else if (test.ID = "swap2") {
share ="33333";
}
else if (test.ID = "swap3") {
share ="44444";
}
document.getElementById("fbshare").innerHTML=share;
}
</script>
Hi, Thanks for spotting my mistake on the getelementsclassname.
For a working demo of the two functions being executed onclick, here it is:
http://jsfiddle.net/79B8z/1/
I found 2 errors.
1. There is no function named getElementByClassName its getElementsByClassName (with an s)
2. document.getElementsByClassName returns a collection of HTMLElement you need the first one so you might have to use an array index notation.
Finally,
It should look like,
var test = document.getElementsByClassName("PortSwap active")[0]
JS Fiddle
To start two functions onclick just use
onclick="next(), fbsharing()"
I think thats what you mean..

Categories