I have a problem when passing data from javascript to bootstrap modal. My code is like following:
Modal:
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title"></h4>
</div>
<div class="modal-body">
<div class="form-group">
<p id="text_from_js"> </p>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Bağla</button>
</div>
</div>
</div>
</div>
My table:
<td align="center" class="comment more">2. Lorem ipsum dolor sit amet, cibo neglegentur ea vis. Mea ut ipsum tincidunt moderatius, eu quo dolorum inermis senserit. Meis zril copiosae nam ea, ea per dico cetero. Sea natum tation feugait ea. Sea te facete dicunt, ei soleat iuvaret omnesque mea. Nam ut tantas atomorum honestatis, no nam saepe quaestio. Te animal ocurreret conclusionemque est
</td>
And javascript code
$(document).ready(function() {
var showChar = 50;
$('.more').each(function() {
var content = $(this).html();
if(content.length > showChar) {
var c = content.substr(0, showChar);
var h = content.substr(showChar-1, content.length - showChar);
var html = c;
$(this).html(html);
}
});
$('.more')
.append(' …')
.click(function() {
document.getElementById("text_from_js").innerHTML = content;
});
});
And how can I pass content to modal which id is text_from_js?
Not quite sure if I understand everthing but try to give the table field data-attributes.
<td align="center" class="comment more" data-id="1" > ... </td>
You can than pass the id with
$('.more').click(function() {
alert( $(this).attr('data-id') );
});
Or if you just want to pass the text to the modal.
$('.more')
.append(' …')
.click(function() {
$("#text_from_js").html( $(this).html() );
});
});
UPDATE:
$(document).ready(function() {
var showChar = 50;
$('.more').each(function() {
var content = $(this).html();
if(content.length > showChar) {
var c = content.substr(0, showChar);
var h = content.substr(showChar-1, content.length - showChar);
var html = c;
/* Store the full content to data-content */
$(this).data('content', $(this).html() );
$(this).html(html);
}
});
$('.more')
.append(' …')
.click(function() {
/* Get the full content from the data-attribute */
document.getElementById("text_from_js").innerHTML = $(this).data('content');
});
});
Related
The problem is simply that I wrote the code below to upload random text and images with the same name but the last number in names changed, but this leads to an increase in the processor temperature,
here is the code :
let ctn=document.getElementById("y_main");
function mainCtn(str,i){
var post= ` <section class="y_post">
<article class="y_post_article">
<h3>${str}</h">
<p> Lorem ipsum dolor sit amet consectetur adipisicing elit.
Enim error dolores nulla vero animi a ex perspiciatis repellendus neque
doloremque! Dolor culpa odio ea, excepturi eaque in similique tempore earum!</p>
<img width="200px" src="image/postimage/img_post${i}.pn" alt="post img">
</article>
<section class="y_post_btn">
<button class="post_lbtn"><img src="icon/check.svg" alt="chat" srcset=""></button>
<button class="post_cobtn"><img src="icon/chat-square-text.svg" alt="chat" srcset=""></button>
<button class="post_shbtn"><img src="icon/share.svg" alt="chat" srcset=""></button>
</section>
<div class="y_comment_block">
<button class="close_btn_comment">close</button>
<p class="text_comment"></p>
<div class="comment_tool">
<textarea name="" class="input_comment" cols="30" rows="1" placeholder="insert comment"></textarea>
<button class="btn_comment">add</button>
</div>
</div>
</section>`
return post;
}
let b=1;
setInterval(function () { if(b<12){
ctn.innerHTML+=mainCtn(`#${b}`,b);b++;
}
else{
clearInterval(myInterval);
}
}, 2000);
Just like #KompjoeFriek mentioned you need the setInterval ID, not an id you hardcode.
let b =1
const myInterval = setInterval(function () {
if(b<12){
ctn.innerHTML+=mainCtn(`#${b}`,b);b++;
} else{
clearInterval(myInterval);
}
}, 2000);
This should work.
I have a bunch of contents that all trigger the same modal. There another way to varying modal without repeat the same code in HTML?
I tried use event.relatedTarget, but without sucess.
Also, the modal is trigger by another div with id modalBtn.
var modal = document.getElementById('modalSpeaker');
var modalBtn = document.getElementById('modalBtn');
var closeBtn = document.getElementsByClassName('closeBtn')[0];
modalBtn.addEventListener('click', openModal);
closeBtn.addEventListener('click', closeModal);
function openModal() {
modal.style.display = 'block';
}
function closeModal() {
modal.style.display = 'none';
}
<div id="modalSpeaker" class="modal">
<div class="modal-content">
<div class="modal-header">
<span class="closeBtn">×</span>
</div>
<div class="modal-body">
<div class="modal-info">
<img src="images/speakers/speaker01.png" alt="">
<h3>Title</h3>
<span>About 01</span>
<span>About 02</span>
</div>
<div class="modal-about">
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Numquam amet consequatur, asperiores blanditiis quis nobis quaerat non aperiam doloribus quae, voluptatibus fuga voluptate porro dolorum velit eaque fugiat autem. Aut.
</p>
<p>
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Modi animi non odit eaque, tempora et fugit vitae officia similique quidem, officiis quisquam esse ipsa enim numquam distinctio sapiente nostrum ratione.
</p>
</div>
</div>
</div>
</div>
You can use a proxy method or a lambda expression (or anonymous function) for your event listener, and pass arguments to your modal display function in order to vary the content in the modal elements.
When you register a function as the callback for an EventListener, you must provide the function reference, but not call it directly. This is because, the EventListener will call the function once the actual event has been fired. This limits your options as far as variability goes on invoking your callback function.
If instead of passing a function reference, you pass a lambda expression, then you can invoke anything you want inside the lambda expression, and this will only be executed once the lambda is invoked when the event is fired.
This gives you the flexibility to define methods with complex argument signatures that can be executed as the result of an event being fired, but with different arguments being passed for each unique event.
There are several other ways to do this as well, but I see this as the cleanest way to accomplish your task.
The below example shows how this can be done:
const modal = document.getElementById('modal');
const title = document.querySelector('#modal .title');
function openModal(color) {
title.innerText = `Selected color: ${color}`;
modal.style.display = 'block';
}
function closeModal() {
modal.style.display = 'none';
}
document.getElementById('modal-close').addEventListener('click', closeModal);
const buttonG = document.getElementById('g-btn');
const buttonR = document.getElementById('r-btn');
const buttonB = document.getElementById('b-btn');
buttonG.addEventListener('click', () => openModal('Green'));
buttonR.addEventListener('click', () => openModal('Red'));
buttonB.addEventListener('click', () => openModal('Blue'));
div#modal {
position: absolute;
top: 0;
left: 0;
width: 300px;
height: 100px;
background: whitesmoke;
display: none;
}
<div id="container">
<span class="title">Click one of the buttons to see the effect...</span>
</div>
<div id="modal">
<div class="title"></div>
<button type="button" id="modal-close">Close</button>
</div>
<button id="g-btn" type="button">Green</button>
<button id="r-btn" type="button">Red</button>
<button id="b-btn" type="button">Blue</button>
Good day everyone,
i am trying to change value of each element inside body by using pure js without any framework.
for example, you open console insert js and it changes all the values in each element of body into other symbols.
So basically i can get all the visible words on the website for user without any html markdowns.
like:
<li>This is text</li>
t->p
h->s
i->e
s->l
e->o
x->z
will be
<li>Psel el pozp</li>
so, don't know how to loop through each elements value.
this is what i tried
var elems = document.body.getElementsByTagName("*");
for (i = 0; i < elems.length; i += 1) {
if (elems[i].innerHTML.indexOf('<script') != -1){
console.log(elems[i]);
} else {
continue;
}
}
function validate(element){
if(element.indexOf('<div') == -1){
return false;
} else if(element.indexOf('<script') == -1){
return false;
} else {
return true;
}
}
but cannot get it to work.
updated:
i think it is my bad. i didnt say that i need to change the values on fly. i mean if i insert the code in console, it should loop through each element, get it value, change values by replacing each letter into another letter, then put the value back instead of the old one. eventually it looks on the web different. thank you in advance.
so i need the code to loop through each element, get its value, do something with it and then put it back.
in bold is what i cannot do. thank you to everyone in advance.
First, in your for loop, add the call to validate. Then in validate, add the text replacement:
var elems = document.body.getElementsByTagName("*");
for (i = 0; i < elems.length; i += 1) {
if (elems[i].innerHTML.indexOf('<script') != -1){
console.log(elems[i]);
} else {
validate(elems[i]);
}
}
function validate(element){
if(element.indexOf('<div') == -1){
return false;
} else if(element.indexOf('<script') == -1){
return false;
} else {
element.innerText = element.innerText.replace("t", "p"); //Add the others as well
}
}
.textContent & .innerText
"So basically I can get all the visible words on the website for user without any HTML markdown." ✱
✱Upper case and grammatical corrections are mine
Text can be extracted from HTML easily just by using .textContent or .innerText properties. There are some significant differences between results and minor inconsistency of standards, see links above and demo below.
Demo
Run the demo and click the Results link or scroll to the very bottom
var content = document.getElementById('content');
var tC = document.getElementById('textContent');
tC.textContent = content.textContent;
var iT = document.getElementById('innerText');
iT.innerText = content.innerText;
<!DOCTYPE html>
<html>
<head>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet">
<style>
html {
scroll-behavior: smooth
}
</style>
</head>
<body>
<div id='content' class='container'>
<header id='top' class='container'>
<hgroup class='row'>
<h1>Home</h1>
</hgroup>
<nav class='row'>
<ul class='nav col-12'>
<li class='p-2'><a href='#a0'>Section 1</a></li>
<li class='p-2'><a href='#a1'>Section 2</a></li>
<li class='p-2'><a href='#a2'>Section 3</a></li>
<li class='p-2'><a href='#a3'>Article</a></li>
<li class='p-2'><a href='#a4'>Results</a></li>
</ul>
</nav>
</header>
<hr>
<main class='container'>
<section id='a0' class='row'>
<article class='col-12'>
<h2>Section I</h2>
<p>Lorem ipsum dolor sit amet, eos nonumy omittam ex. No dicant tibique accusamus pri, sed omnis posidonium ad. In sea dico honestatis, ex repudiare reprimique delicatissimi mea. Sit dicta moderatius ad, natum convenire usu ei. Est no graece laboramus
deterruisset. </p>
</article>
</section>
<section id='a1' class='row'>
<article class='col-12'>
<h2>Section II</h2>
<p>Mundi nemore iisque in nec. An dolorum intellegat conclusionemque eos, ad labore omittam mel. Te nam wisi omittam patrioque, oporteat honestatis intellegebat cu mei. Odio cibo omittantur te sed.</p>
</article>
</section>
<section id='a2' class='row'>
<article class='col-12'>
<h2>Section III</h2>
<p>Alii commodo ne sea, eu pro legimus signiferumque. At mei nisl facete adolescens, et mel eleifend voluptatibus. Qui ei wisi sonet noster, est solum posidonium scribentur et, sea nobis verear ut. Nemore admodum usu ne.</p>
</article>
</section>
<hr>
<section id='a3' class='row'>
<article class='col-12'>
<h2>Article</h2>
<p>Lorem ipsum dolor sit amet, quot erroribus voluptatum in pri. Fabulas vocibus insolens his ex. Vide laboramus ius et, at sit adhuc doctus luptatum, et sit dicat inani democritum. His liber blandit pericula id, an fugit reformidans neglegentur
cum. Indoctum intellegat et pro, sed fabulas ocurreret eu. Nam ut fabulas inciderint, iracundia conceptam ne vix, quo offendit inimicus torquatos in.</p>
<div class='row'>
<aside class='col-4 float-left'>
<blockquote>
<p>Duo illum assum discere ne, sed cu posse alterum accusam. Cum an error pertinacia, aperiam deleniti</p>
</blockquote>
</aside>
<p class='col-8'>Ut has elit labores, ex animal delectus efficiendi eos. Id soleat accusamus mel, sint deterruisset his an. Civibus fabellas interpretaris vis ea, dicat aperiri nec ut. Et posidonium dissentias ius, essent quodsi no nam. Mei graece prompta
quaestio et, pri no voluptua atomorum. Pri id putant graecis. Autem prompta nostrud ut mei, mea ut facilisis expetenda intellegebat.</p>
</div>
<div class='row'>
<p class='col-12'>Quo dolor commune albucius ea, ad novum senserit mediocritatem pro, te nisl quidam intellegam nam. Audire omittam in sea, per veniam noster ne. Duo illum assum discere ne, sed cu posse alterum accusam. Cum an error pertinacia, aperiam deleniti
sedcu. Pri ut facilisi hendrerit reformidans, id qui modus libris deseruisse, cum primis moderatius ut.</p>
</div>
</article>
</section>
</main>
<hr>
<footer class='container'>
<nav class='row'>
<ul class='nav col-12'>
<li><a href='#top'>HOME</a></li>
</ul>
</nav>
</footer>
</div>
<!--End of #content-->
<hr>
<hr>
<section id='a4' class='container'>
<h2>Results</h2>
<div class='container'>
<div class='row'>
<h3><code>textContent</code></h3>
<div id='textContent' class='col-10'></div>
</div>
<hr>
<div class='row'>
<h3><code>innerText</code></h3>
<div id='innerText' class='col-10'></div>
</div>
</div>
</section>
<script>
</script>
</body>
</html>
Your code as you have posted does not call the validate function so I will totally ignore that. Your stated objective is really not super clear however I will put an attempt to loop through some elements with something similar to what you have.
For my code, I add a class to everything that is not skipped; that is where you would do your processing; call your function etc. i.e. el.classList.add("show-processors");
Note:skipList an the function filterBySkipCheck are the key parts here.
function doSomething(el) {
const showplace = document.getElementById('actions-display')
.getElementsByClassName('showme')[0];
showplace.innerText = showplace.innerText + el.innerText;
const textContentOutput = document.getElementById('textContentOutput');
const innerTextOutput = document.getElementById('innerTextOutput');
textContentOutput.innerHTML = el.textContent;
innerTextOutput.innerHTML = el.innerText;
}
function hasParentWithMatchingSelector(target, selector) {
return [...document.querySelectorAll(selector)].some(el =>
el !== target && el.contains(target)
);
}
function hasMatchingSelector(target, selector) {
return [...document.querySelectorAll(selector)].some(el =>
el === target
);
}
function hasClass(element, classname) {
return element.classList.contains(classname);;
}
function hasSelfOrParentWithClass(element, classname) {
if (element.classList.contains(classname)) return true;
return element.parentNode && hasSelfOrParentWithClass(element.parentNode, classname);
}
function hasParentWithClass(element, classname) {
return hasParentWithMatchingSelector(element, '.' + classname);
}
function filterBySkipCheck(el, index, myarr, skipList) {
let isSkipped = false;
// process each item in skip list
skipList.forEach(function(skip) {
if (!isSkipped && skip.matchType === 'tag') {
isSkipped = el.tagName === skip.match;
}
if (!isSkipped && skip.matchType === 'skipclass') {
isSkipped = hasClass(el, skip.match);
}
if (!isSkipped && skip.matchType === 'selector') {
isSkipped = hasMatchingSelector(el, skip.match);
}
if (!isSkipped && skip.matchType === 'parentselector') {
isSkipped = hasParentWithMatchingSelector(el, skip.match);
}
if (!isSkipped && skip.matchType === 'element') {
isSkipped = el === skip.match;
}
});
return isSkipped;
}
function processAllElements(elements, skipL) {
// filter for stuff to skip
const filteredElements = [...elements].filter(function(el, index, myarr) {
return filterBySkipCheck(el, index, myarr, skipL);
});
// this answers the question, how to process/loop through all but also how to filter
for (let i = 0; i < elements.length; i += 1) {
let el = elements[i];
let isSkipped = filteredElements.includes(elements[i]);
let shouldProcess = !isSkipped;
if (shouldProcess) {
el.classList.add("show-processors");
}
}
}
let skipList = [{
match: "SECTION",
matchType: "tag"
}, {
match: "SCRIPT",
matchType: "tag"
}, {
match: "STYLE",
matchType: "tag"
}, {
match: "skipme-also",
matchType: "skipclass"
}, {
match: ".skipme",
matchType: "selector"
}, {
match: ".skipme",
matchType: "parentselector"
}, {
match: document.getElementById('second-skip'),
matchType: "element"
}];
let elementsInScope = document.body.getElementsByTagName("*");
processAllElements(elementsInScope, skipList);
.show-processors {
border: solid 1px red;
}
.show-skippers {
border: solid 1px green;
}
<script>
var myfriend = "pluto";
</script>
<div>first</div>
<div id='second-skip'>second</div>
<div>nested one
<div>nested inner
<div>nested granchild</div>
</div>
</div>
<div>container for list
<ul>in the list
<li>one</li>
<li>two</li>
<li>three</li>
<li>four</li>
</ul>
</div>
<div>testlink
<button type="button">button</button>
<span>span1</span><span>spanner2</span>
</div>
<section>test section to skip</section>
<div class="skipme-also">I am skipped</div>
<div class="skipme">skip me by class</div>
<div>I contain paragraphs
<p>Happy day</p>
<p>Happy day2</p>
<p>Happy day3</p>after paragraphs
</div>
<div id="actions-display" class="skipme">I just show stuff
<button id="test-button" type="text">Click to test</button>
<div class="showme"></div>
<h3>Result of textContent:</h3>
<textarea id="textContentOutput" rows="6" cols="30" readonly>...</textarea>
<h3>Result of innerText:</h3>
<textarea id="innerTextOutput" rows="6" cols="30" readonly>...</textarea> JavaScript
</div>
I have created an advent calander, the link is:- http://www.project-progress.co.uk/westcoast/advent/
However I have the problem that clicking close when the popup is open, you then cannot reopen this popup.
This is my HTML:-
<ul>
<div class="left-title">
<img src="/westcoast/advent/wp-content/uploads/images/quizmass.jpg" width="280px" />
<p class="sh">Lorem ipsum dolor sit amet, ut cum omnis accumsan eleifend. Ei animal splendide eum, vis liber ocurreret forensibus.<br><br>
Lorem ipsum dolor sit amet, ut cum omnis accumsan eleifend. Ei animal splendide eum, vis liber ocurreret forensibus.
</p>
</div>
<li>
<div class="door">
<img src="/westcoast/advent/wp-content/uploads/images/days/1.png" />
<span>1</span>
</div>
<div class="door-popup">
<div class="half-l">
<img src="/westcoast/advent/wp-content/uploads/images/days/popup/1a.png"/>
</div>
<div class="half-r">
<div class="cross">
<img src="/westcoast/advent/wp-content/uploads/images/cross.png" />
</div>
<div class="pad">
detail </div>
</div>
<div class="clear"></div>
</div>
</li>
<li>
<div class="door">
<img src="/westcoast/advent/wp-content/uploads/images/days/2.png" />
<span>2</span>
</div>
<div class="door-popup">
<div class="half-l">
<img src="/westcoast/advent/wp-content/uploads/images/days/popup/2a.png"/>
</div>
<div class="half-r">
<div class="cross">
<img src="/westcoast/advent/wp-content/uploads/images/cross.png" />
</div>
<div class="pad">
detail </div>
</div>
<div class="clear"></div>
</div>
</li>
And my JQuery is:-
$(document).ready(function () {
var message = "";
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var scrolled = false;
var timeDelay = 200;
// function to reveal message
var cardReveal = function () {
$("#message").text(message).show();
}
day=1; //Comment me out
// Only work in December
if (month === 11) {
// Loop through each calendar window
$(".container ul li").each(function (index) {
var adventwindow = index + 1;
var item = $(this);
// Add words so far to message variable
if (adventwindow <= day) {
var word = words[index];
$(this).append('<div class="revealed">' + word + '</div>');
message = message + " " + word;
}
// On clicking a window, toggle it open/closed and
// handle other things such as removing jiggle and 25th
$(".container ul li").on("click", function () {
if (adventwindow <= day) {
$(this).children().find(".door").addClass("openlive");
$(this).children(".door-popup").fadeIn();
$(".overlay").fadeIn();
$(".door-popup").appendTo('body');
$(this).find('.openlive img, .openlive span').fadeOut();
setTimeout(function(){
$('.revealed').fadeIn();
}, 300);
event.stopPropagation();
}
//else {
//alert("Please check back on the correct day, to see more prizes")
//}
$(this).removeClass("jiggle");
});
});
$( ".cross" ).click(function() {
if($(this).parent().parent().css("display") == "block"){
$(this).parent().parent().hide();
$('.overlay').hide();
event.stopPropagation();
}
else{
}
});
}
});
Does anyone have any ideas? It seems as though I need to kind of reset the function one the cross has been clicked.
Thank you all.
Scott
I'm trying Jquery and now I have a problem.
I want to remove an element from my webpage. So, when I press the delete button - the big element must disappear. Using the JQ I have written something like this
$(document).ready(function(){
$(".delete").click(function(){
$(this).parents(".block").animate({ opacity: 'hide' }, "slow");
})
});
It have worked fine until I didn't add subdiv, or answer. And how the application must works now? I press the delete button and it must remove current block.
<div class = "block">
<div class = "postbuttons">
<img src = "img/delete-icon.png" class = "delete"></a>
<img src = "img/edit-icon.png" class = "edit"></a>
</div>
<div class = "postinfo">
<span class = "author">Da Monkey wrote:</span> <span class = "date">on <span>13.13.13</span></span>
</div>
<div class = "post">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea, voluptate, unde, impedit iste sint assumenda consequatur ipsum nesciunt</p>
<a class = "answerlink" href = "#">Answer</a>
</div>
<div class = "answer">
<div class = "postbuttons">
<img src = "img/delete-icon.png" class = "delete"></a>
<img src = "img/edit-icon.png" class = "edit"></a>
</div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fuga, numquam, culpa, omnis explicabo ut asperiores ipsam porro alias quisquam nisi iste non a maiores! Nulla odio unde dolorum officia vero. </p>
<div class = "answerinfo">
- Macaque on <span>13.13.13</span>
</div>
</div>
If you didn't understand me here the result
Respect to the funcionality:
$(document).ready(function(){
$(".delete").click(function(){
$(this).closest(".block").animate({ opacity: 'hide' }, "slow");
});
});
you should use closest instead of parents because it stop once it has found the first math and parents travels to the root of the dom. Also if you dont need the block anymore you can remove it with the jquery method remove(), after tue animation ended with a callback function.
Also you are missing some semicolons, and tags
$(document).ready(function(){
$(".delete").click(function(){
$(this).parents(".block").animate({ opacity: 'hide' }, "slow");
}) // here needs a semicolon
});
Missing tags
<div class = "block">
<div class = "postbuttons">
<img src = "img/delete-icon.png" class = "delete"></a> <--! missing <a> -->
<img src = "img/edit-icon.png" class = "edit"></a> <--! missing <a> -->
</div>
<div class = "postinfo">
<span class = "author">Da Monkey wrote:</span> <span class = "date">on <span>13.13.13</span></span>
</div>
<div class = "post">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea, voluptate, unde, impedit iste sint assumenda consequatur ipsum nesciunt</p>
<a class = "answerlink" href = "#">Answer</a>
</div>
<div class = "answer">
<div class = "postbuttons">
<img src = "img/delete-icon.png" class = "delete"></a> <--! missing <a> -->
<img src = "img/edit-icon.png" class = "edit"></a> <--! missing <a> -->
</div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fuga, numquam, culpa, omnis explicabo ut asperiores ipsam porro alias quisquam nisi iste non a maiores! Nulla odio unde dolorum officia vero. </p>
<div class = "answerinfo">
- Macaque on <span>13.13.13</span>
</div>
</div>
I hope I was Useful.
Try hiding the container of the container of the delete button, which will work regardless of its class:
$(document).ready(function(){
$(".delete").click(function(){
$(this).parents(".postbuttons").parent().animate({ opacity: 'hide' }, "slow");
})
});