read class and apply css with javascript or jquery - javascript

I wanna apply css with short class name with number.
for example,
if I use class name mt-100, it means margin-top:100px.
if I use class name mr-200, it means margin-right:200px.
if I use class name mt-100 mr-200, it means margin-top:100px and margin-right:200px.
if I use class name pt-100 mt-100 mr-200, it means padding-top:100px and margin-top:100px and margin-right:200px.
I try to make it but it does not work.
I do not want to make every class in css like this --> .mt-100{margin-top:100}
could you help me how to do make this?
thank you in advance.
let me show you my code below,
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
function classStartsWith(str) {
return $('div').map( function(i,e) {
var classes = e.className.split(' ');
for (var i=0, j=classes.length; i < j; i++) {
if (classes[i].substr(0, str.length) == str) return e;
}
}).get();
}
function classEndWith(str) {
return $('div').map( function(i,e) {
var classes = e.className.split(' ');
for (var i=0, j=classes.length; i < j; i++) {
if (classes[i].indexOf('mt-') || classes[i].indexOf('mb-') || classes [i].indexOf('mr-') || classes[i].indexOf('ml-') || classes[i].indexOf('pt-') || classes[i].indexOf('pb-') || classes[i].indexOf('pr-') || classes[i].indexOf('pl-'))
{
var ct = classes[i].split('-');
var cts = ct[1];
}
if (classes[i].substr(0, str.length) == str) return e,cts;
}
}).get();
}
$(document).ready(function(){
$(classStartsWith('mt-')).each(function(){
$(this).css('margin-top', classEndWith('mt-')+'px');
});
$(classStartsWith('mb-')).each(function(){
$(this).css('margin-bottom', classEndWith('mb-')+'px');
});
$(classStartsWith('mr-')).each(function(){
$(this).css('margin-right', classEndWith('mr-')+'px');
});
$(classStartsWith('ml-')).each(function(){
$(this).css('margin-left', classEndWith('ml-')+'px');
});
$(classStartsWith('pt-')).each(function(){
$(this).css('padding-top', classEndWith('pt-')+'px');
});
$(classStartsWith('pb-')).each(function(){
$(this).css('padding-bottom', classEndWith('pb-')+'px');
});
$(classStartsWith('pr-')).each(function(){
$(this).css('padding-right', classEndWith('pr-')+'px');
});
$(classStartsWith('pl-')).each(function(){
$(this).css('padding-left', classEndWith('pl-')+'px');
});
});
</script>
</head>
<body>
<div class="mt-100 mb-200" style="width:300px;height:300px;border:1px solid red">
aaaa
</div>
<div class="pt-200 mb-200" style="width:300px;height:300px;border:1px solid red">
bbb
</div>
<div class="pr-300 ml-300 mt300" style="width:300px;height:300px;border:1px solid red">
ccc
</div>
<div class="pl-200 mt200" style="width:300px;height:300px;border:1px solid red">
ddd
</div>
</body>

The way you handle it now presents way too much overhead for this kind of task.
I recommend you to learn more about using the data attribute on your HTML tags. These attributes allow you to define tag specific settings which you can easily read with jQuery and make it respond to the data.
Example:
<div class="my-div-class" data-mt="100" data-mb="200">...</div>
<div class="my-div-class" data-pt="200" data-mb="200">...</div>
<script>
$(function() {
// Walk through each element with this class
$('.my-div-class').each(function() {
var thisDiv = $(this), // cache this element
thisData = thisDiv.data(), // get all data attributes
thisCSS = {}; // create the css array
// Check which data is set and update the css accordingly
if (thisData['mt']) {
thisCSS['margin-top'] = thisData['mt'] + 'px';
}
if (thisData['mb']) {
thisCSS['margin-bottom'] = thisData['mb'] + 'px';
}
if (thisData['pt']) {
thisCSS['padding-top'] = thisData['pt'] + 'px';
}
if (thisData['pb']) {
thisCSS['padding-bottom'] = thisData['pb'] + 'px';
}
// Add the css to this element
thisDiv.css(thisCSS);
// The following two lines show the data in each div for debugging.
// Remove these lines when you don't need this info anymore.
thisDiv.append('<div>CSS: ' + JSON.stringify(thisCSS) + '</div>');
thisDiv.append('<div>DATA: ' + JSON.stringify(thisData) + '</div>');
});
});
</script>
Here is the JSFiddle.
And here is the jQuery Documentation on .data().
Also check out the data-attribute documentation here.

Related

Use Javascript to write names that don't appear in master list to div with id

Working demo at http://verlager.com/pairing.php uses document.write() but I would prefer to write to a div's ID. I have tried several methods but I can't get the for loop to write to div with id of "textDiv".
<script>
function newly_minted() {
var res = "Attaya, James J|Blazak, Stephen A|Cavanaugh, Michael P|Decker, Howard|";
document.getElementById("textDiv").textContent = res;
}
newly_minted();
</script>
<div id="textDiv" style="background:green; color:fff; display:table; height:10rem; width:40rem; margin:4rem auto; clear:both;"></div>
For original post:
This code replaces textDiv content because of the simple assignment used:
var div = document.getElementById("textDiv");
div.textContent = resort;
var text = div.textContent; //should append not replace!
Try the '+=' operator instead:
var div = document.getElementById("textDiv");
div.textContent += resort;
var text = div.textContent; //should append not replace!
For the updated post:
Declare newly_minted before calling it from a different script element. Hoisting function declarations only applies to the script element in which the function is declared.
Replace $( resort) with resort (and split resort on "|" as in the original). The trailing "|" is not altered in this demonstration:
function newly_minted() {
var res = "Attaya, James J|Blazak, Stephen A|Cavanaugh, Michael P|Decker, Howard|".split('|');
for (let i = 0; i < res.length; i++) {
var resort = res[i] + " ● ";
$( "#textDiv" ).append(resort);
}}
newly_minted();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="textDiv"></div>
Alternatively, without using jQuery, preparing text content first and removing trailing dots:
function newly_minted() {
var res = "Attaya, James J|Blazak, Stephen A|Cavanaugh, Michael P|Decker, Howard|".split('|');
for (var i = 0, text =""; i < res.length; i++) {
text += res[i] + " \u25cf ";
}
text = text.replace(" \u25cf \u25cf ", ""); // remove two trailing dots
document.getElementById("textDiv").textContent = text;
}
newly_minted();
<div id="textDiv"></div>

Need help calling a function with parameters in JavaScript

I am working on a college project which is basically an elaborate news summarizer. I need to dynamically generate a list of article headings upon clicking a topic.
I have been able to do that and assign the list Ids and Values dynamically using the for loop.
Each list is clickable and calls a parameterized function, with parameter as that lists value.
I am unsure how to define the function and syntax to make this a possibility.
I need to do this so that each heading when clicked can use AJAX to interact with a servlet and generate an article corresponding to the heading based on their values.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
function change() {
var i = 0;
var set;
document.getElementById('content').innerHTML = '';
for (i = 1; i < 6; i++) {
var div = document.getElementById('content');
div.innerHTML = div.innerHTML + '<a href="#" onClick="rem()">'
+ '<h2 id="theading'+i+'" value="'+i+'">HEADING ' + i
+ ' WILL GO HERE</h2></a><br>';
}
}
function rem(value) {
document.getElementById('content').innerHTML = value
+ '<h1>THE NEWS WILL GO HERE</h1>';
}
</script>
</head>
<style type="text/css">
* {
list-style: none;
}
a {
text-decoration: none;
color: inherit;
}
a:hover {
color: orange;
}
</style>
<body>
<h3>TOPIC</h3>
<div id="content"></div>
</body>
</html>
How do I write the code so that rem() function can be called with its parameter as the value of its corresponding list.
I would completely rewrite your first function:
function change() {
var i = 0;
var set;
var div = document.getElementById('content');
div.innerHTML = '';
for (i = 1; i < 6; i++) {
var a = document.createElement('a');
a.href = "#";
a.onclick = rem.bind(null, i); // Here is the magical part
a.innerHTML = '<h2 id="theading'+i+'">HEADING ' + i
+ ' WILL GO HERE</h2>';
div.appendChild(a);
div.appendChild(document.createElement('br'));
}
}
Embrace the power of this.
onClick="rem(this)"
This will pass a reference to the clicked element. From there you can then traverse the DOM, using parents and children, to locate other elements, without having to deal with messy IDs.
You need to pass that value to method rem().
I am not absolute sure which value you wan't to pass for it but changing:
onclick="rem()"
to:
onclick="rem(' + i + ')"
will call method rem with an value of i when the link is clicked.
After that you can and should discard value="'+i+' from your h2 tag. It is not valid HTML.
Cheers.

How to write all data from Array?

I have HTML like :
<div id="divid">
1
2
3
.....................
</div>
I have script to get all links from a div like :
<script>
var links = document.getElementById('divid').getElementsByTagName('a') ;
</script>
Then I want write link into class like :
<script>
var links = document.getElementById('divid').getElementsByTagName('a') ;
document.write("<div class="'+link[1]+" "+ link[i]+'">Class is added links</div>");
</script>
That mean after write I have HTML:
<div class="d#link1 d#link2 d#link3">Classes is added links</div>
How can I do this? Using for loop or not? how?
You have to get the href property from each element. Put them in an array, and you can just join the strings:
var elements = document.getElementById('divid').getElementsByTagName('a');
var links = [];
for (var i = 0; i < elements.length; i++) {
links.push(elements[i].href);
}
document.write("<div class="' + links.join(" ") + '">Class is added links</div>");
Use join in combination with map:
var classString = links.map(function(link) { return link.attributes.href; } ).join(' ');

Regular expression getElementById

I need to use pure Javascript for the first time in a long while, and having gotten used to the comfy mattress of jQuery, all the important stuff is escaping me.
I need to select a bunch of divs on regular expression. So I have stuff like this;
<div id="id_123456_7890123"> .. </div>
<div id="id_123456_1120092"> .. </div>
<div id="id_555222_1200192"> .. </div>
<div id="id_123456_9882311"> .. </div>
And I'd need to create a loop that goes through all the divs with an id that begins with id_123456_. How would I go about doing that?
I used jQuery with the :regex filter plugin before, but looking at it, it doesn't seem like there's much I could salvage in a pure javascript rewrite.
In plain javascript, you could do this generic search which should work in every browser:
var divs = document.getElementsByTagName("div"), item;
for (var i = 0, len = divs.length; i < len; i++) {
item = divs[i];
if (item.id && item.id.indexOf("id_123456_") == 0) {
// item.id starts with id_123456_
}
}
Working example: http://jsfiddle.net/jfriend00/pYSCq/
HTML DOM querySelectorAll() method will work here.
document.querySelectorAll('[id^="id_"]');
Borrowed from StackOverFlow here
This works by recursively traversing the whole DOM.
It's possibly not the most efficient, but should work on every browser.
function find_by_id(el, re, s) {
s = s || [];
if (el.tagName === 'DIV' && re.exec(el.id) !== null) {
s.push(el);
}
var c = el.firstChild;
while (c) {
find_by_id(c, re, s);
c = c.nextSibling;
}
return s;
}
var d = find_by_id(document.body, /^id_123456_/);
See http://jsfiddle.net/alnitak/fgSph/
Here you are: http://jsfiddle.net/howderek/L4z9Z/
HTML:
<div id="nums">
<div id="id_123456_7890123">Hey</div>
<div id="id_123456_1120092">Hello</div>
<div id="id_555222_1200192">Sup</div>
<div id="id_123456_9882311">Boom</div>
</div>
<br/>
<br/>
<div id="result"></div>​
Javascript:
divs = document.getElementsByTagName("div");
divsWith123456 = new Array();
for (var i = 0;i < divs.length;i++) {
if (divs[i].id.match("id_123456") != null) {
divsWith123456.push(divs[i]);
document.getElementById("result").innerHTML += "Found: divs[" + i + "] id contains id_123456, its content is \"" + divs[i].innerHTML + "\"<br/><br/>";
}
}​

Dynamically generating a button using DOM and editing onclick event

I trying to generate an input (type="button") and setting the onclick-Event to a function, which should hand over a parameter. The whole object should be appended to a div and thats it. Basically this is my try, but I can't see why it does not work.
I pasted the code to jsfiddle, hence its easier for you to reproduce. Click here.
What am I'm doing wrong? I'm learning it by trial and error, so please explain whats wrong. Thanks a lot!
[edit] for the case jsfiddle will be down one day, here is the code I tried to run... :)
<!doctype html>
<html>
<head>
<title>onclick event example</title>
<script type="text/javascript" language="javascript">
var i = 0;
var h = new Array();
function addButton() {
i++;
var container = document.getElementById("check0");
var h[i] = document.createElement("input");
h[i].type = 'button';
h[i].name = 'number' + i;
h[i].value = "number" + i;
h[i].id = 'number' + i;
h[i].onclick = function() {
showAlert(i)
};
container.appendChild(h[i]);
}
function showAlert(number) {
alert("You clicked Button " + number);
}​
</script>
</head>
<body>
<div id="check0">
<input type="button" value="klick mich" id="number0" onclick="addButton()"/>
</div>​
</body>
</html>
Here is the fixed fiddle for you.
var h[i] = ... is invalid JavaScript.
What you write in the "JavaScript" frame on jsfiddle is executed onload, so this code is not yet present when the HTML you provide is executed (and neither is the addButton() function).
<script>
var i = 0;
var h = new Array();
function addButton() {
i++;
var container = document.getElementById("check0");
h[i] = document.createElement("input");
h[i].type = 'button';
h[i].name = 'number' + i;
h[i].value = "number" + i;
h[i].id = 'number' + i;
h[i].onclick = function() {
showAlert(i)
};
container.appendChild(h[i]);
}
function showAlert(number) {
alert("You clicked Button " + number);
}
</script>
<div id="check0">
<input type="button" value="klick mich" id="number0" onclick="addButton()"/>
</div>​
Try using h.push(...) instead of trying to send to a non created element in the array
var x = document.getElementById('pagination');//pagination is an empty div in html
var y ='';
for(var i = 0; i <= (pageMax); i++){
y = y+"<a id ='pageNumber"+i+"' onclick='changePage("+(i+1)+");'>"+(i+1)+"</a>\n ";
} x.innerHTML=y }
i used this to make a pagination for a table. The function will create a row of numbers until button max. 'changePage("+(i+1)+"); ... will call a function and send the i index(number that the page is) of the pagenumber. also i dynamically create a id unique for each number.

Categories