Update DOM of popup.html after clicking button - javascript

I am making a chrome extension. I want to update a h3 element in popup.html with some text after click a submit button with id submit.
<!-- popup.html -->
<div class="row">
<h3 id="status"></h3>
</div>
// popup.js
function saveClass() {
var status = document.getElementById('status')
status.innerText = 'success';
}
document.getElementById("submit").addEventListener("click", saveClass);
The function populates the element with the text, and I see the text, but it disappears immediately, within some microseconds. Where I am going wrong ?

For me its' working fine. You can refer the following code snippet
<html>
<body>
<!-- popup.html -->
<div class="row">
<h3 id="status"></h3>
</div>
<button id="submit">Submit</button>
<!-- popup.js -->
<script>
function saveClass() {
var status = document.getElementById('status')
status.innerText = 'success';
}
document.getElementById("submit").addEventListener("click", saveClass);
</script>
</body>
</html>

The form refreshes the page by default upon submission, due to which the populated text vanishes. Just add an event listener to disable it, which keeps the DOM intact.
var form = document.getElementById("myForm");
function handleForm(event) { event.preventDefault(); }
form.addEventListener('submit', handleForm);

Related

I'm can't append a div created in js file inside a <section>, whitch is inside a grid, in my index.html

I'm trying to create a to-do list and use html/css/js to do it.
I've created a button, and a text input on HTML.
Created a function in JS.
Got both by their id.
Created a div in JS.
inserted the the text that I got from text input inside the var that holds the div.
and tryied to append this div into the section using appenddChild.
When I click the button I can see the div apearing for less than a second inside the section, and it desapears.
function addTask() {
let userInput = document.getElementById("add-field").value;
let task = document.createElement("div");
task.innerText = userInput;
taskList = document.getElementById("list");
task.className = "task-bar";
document.querySelector('#list').appendChild(task);
}
<main id="container">
<section id="entrance">
<h1>TASKS</h1>
</section>
<section id="adding">
<form id="adding-items">
<input id="add-field" type="text">
<button id="send-btn" value="ADD" onclick="addTask()">ADD</button>
</form>
</section>
<section id="list">
</section>
</main>
You are using a form element.
So if you click the button, it would refresh the page.
To prevent it, you can use onSubmit="return false;".
<form onSubmit="return false;" id="adding-items">
Its because you're using a <form> element. Forms have a default behavior that when it contains a button, that button will be used to submit the form, unless the type of the button is other than submit.
You'll need to stop the default behavior of the form from happening. You do this by preventing the default behavior of the submit event.
You do this with Event.preventDefault() inside the event handler.
const form = document.querySelector('#adding-items');
const taskList = document.querySelector('#list');
const userInput = document.getElementById("add-field")
function addTask() {
let userInputValue = userInput.value;
let task = document.createElement("div");
task.innerText = userInputValue;
task.className = "task-bar";
taskList.appendChild(task);
}
form.addEventListener('submit', event => {
event.preventDefault(); // Stop the default behavior.
addTask();
});
<main id="container">
<section id="entrance">
<h1>TASKS</h1>
</section>
<section id="adding">
<form id="adding-items">
<input id="add-field" type="text">
<button id="send-btn" value="ADD">ADD</button>
</form>
</section>
<section id="list">
</section>
</main>

document.createElement flashes up with what I want. Then it disappears

I'm having a small issue with my code. I want the user's input to appear on the screen, like a chatbot. However, it is not doing this. What it's doing instead is flashing up with what I want. Then it is disappearing. Just the message, not the entire thing, but that sometimes happens as well. What has happened and how can I fix it?
function executeNewMessage() {
var messagecontainer = document.getElementById("message");
var message = messagecontainer.value;
var newmessagediv = document.createElement("DIV");
newmessagediv.innerHTML = message;
document.getElementById("bodymessages").appendChild(newmessagediv);
}
<div id="site">
<div id="head">
Chatbot
</div>
<div id="body">
<div id="bodymessages"></div>
<span id="bottom"></span>
</div>
<div id="foot">
<form>
<label for="message">Type your message here</label>
<input id="message" type="text" />
<a href="#bottom">
<button id="submit" onclick="executeNewMessage()">→</button>
</a>
</form>
</div>
</div>
The reason that this is happening is because you are using HTML form. The default behavior for form is that they try to submit to the server. That's why you only see the change for a short duration and the page reloads again. Hence, you need to use preventDefault() method.
So, your function should look like this:
function executeNewMessage(e) { //Here e is the event object
var messagecontainer = document.getElementById("message");
var message = messagecontainer.value;
var newmessagediv = document.createElement("DIV");
newmessagediv.innerHTML = message;
document.getElementById("bodymessages").appendChild(newmessagediv);
e.preventDefault();
}
So, what the preventDefault() does is that it prevents the default action of an event.
https://www.w3schools.com/jsref/event_preventdefault.asp

use Jquery to click hyperlink

I am trying to create a jquery to click a hyperlink but nothing seems to be working.
HTML
<main id="main" class="main-content">
<div class="container">
<div class="warning" role="alert">
no avail
Show all
</div>
what I was trying
$(".warning a").click()
Any suggestions?
Note that jQuery-initiated "click" events will fire the event but will not cause navigation to occur.
Instead you can read the link's HREF attribute and directly set the window location:
// The click event:
$('a').on("click", function() {
console.log("Click event fired");
})
var demo1 = function() {
// This will trigger the click event, but will not navigate.
$(".warning a").click()
}
var demo2 = function() {
// This will navigate but will not trigger the click event. (If you need both to happen, trigger the click event first, and consider delaying the window location update if necessary.)
var url = $(".warning a").attr("href")
window.location = url;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main id="main" class="main-content">
<div class="container">
<div class="warning" role="alert">
Show all
</div>
</div>
</main>
<!-- for demo: -->
<button onclick="demo1()">Won't work</button>
<button onclick="demo2()">Will work</button>
jQuery's .click() (without arguments) is a shortcut for .trigger("click"):
function(a,c) {
return arguments.length > 0 ? this.on(b, null, a, c) : this.trigger(b)
}
Therefore, it will not actually click the element, but just call the click event handlers attached to it, as you can see here:
const $link = $("a");
$link.on("click", () => {
console.log("Clicked? Not really...");
});
$link.click();
$link.trigger("click");
Show all
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You need to get a reference to the actual DOM element and then call HTMLElement.click() on that:
$("a")[0].click();
Show all
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can user the vanilla click method:
document.querySelector('.warning > a').click()
// equivalent jquery
//$('.warning > a')[0].click()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="warning" role="alert">
no avail
Show all
</div>
Whenever you select div class with hyperlink there you get array because you can have multiple hyperlinks so you need to add somthing like below
Code
$('.warning a')[0].click();
For reference link
Get working example for click event
If I need to redirect, I typically use window.location.href
window.location.href=$(".warning a").attr('href');

update div content of iframe on button

i want to update div content (content form textarea of main page) of iframe on button click.
up till now i'm able to update div content (content from textarea of main page) of iframe but its done only on page load, i want to change content on button.
my script working on page load
$(function(){
var x = document.getElementById("myTextarea").value;
var f=$('#prev')
f.load(function(){
f.contents().find('#demo').append(x);
})
})
my script not-working on button click but alert called with latest text from textarea
function myFunction() {
var x = document.getElementById("myTextarea").value;
alert("called" + x);
var f=$('#prev')
f.load(function(){
f.contents().find('#demo').append(x);
})
}
iframe in modelpopup
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-lg" style="width:90%;height:100%!important;">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Html Preview</h4>
<button type="button" class="btn btn-default" onclick="myFunction()">Refresh</button>
</div>
<div class="modal-body">
<iframe id="prev" src="http://localhost:8084/page/htmlpreview" style="border:none;width:100% !important;height:1025px!important;"><p>Your browser does not support iframes.</p></iframe>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
any suggestions...
In the OP code there's no <textarea> just a BS modal. According to the OP code the <textarea> should be on the parent page (in demo: index.html) and the div#demo is on the child page (in demo: htmlpreview.html.) So in the demo we have:
the parent page (index.html) with textarea#text0 and a <button>
and the child page (htmlpreview.html) that resides within iframe#prev
on the child is div#demo
When the <button> is clicked the onevent attribute invokes the event handler xFunction().
When xFunction() is invoked it will:
get the value of textarea#text0 [var x = $('#text0').val();]
access iframe#prev contents [$('#prev')..contents()...]
then find div#demo [....find('#demo')...]
and set div#demo text content to the value of textarea#text0 [....text(x)]
The demo doesn't function due to SO security measures. Review this Plunk instead.
index.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<textarea id='text0' rows='5' cols='70'></textarea>
<button type="button" onclick="xFunction()">Refresh</button>
<iframe id="prev" src="htmlpreview.html"></iframe>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function xFunction() {
var x = $("#text0").val();
$('#prev').contents().find('#demo').text(x);
}
</script>
</body>
</html>
htmlpreview.html
<!DOCTYPE html>
<html>
<head>
<style>
#demo {border:3px solid red}
</style>
</head>
<body>
<div id='demo'></div>
</body>
</html>
The above two scripts change to this one script and its working perfect
i have to reload iframe the make desire div empty then edit content.
below is the working script.
function myFunction() {
var ifr = document.getElementsByName('Right')[0];
ifr.src = ifr.src;
var x = document.getElementById("myTextarea").value;
var f=$('#prev')
f.load(function(){
f.contents().find('#demo').empty();
f.contents().find('#demo').append(x);
})
}
I am not sure this can be done by handling the DOM of the iframe as you might expect. According to this answer
However according to some other answers in the above link or this you could change the entire content of the iframe with what the content you want. (Including the change that you want.) I know this doesn't seem as the best solution but keep it in mind in case you don't find anything else.
One link with such a logic is this. Here you can get the innerHTML of the iframe and possibly find from the string the literal you want to change and set the new content as the iframe content.
The helping code from the link that shows the logic is this:
function get_iframe(ifr_id) {
// gets the object that refers to the iframe, uasing its id
var myIFrame = document.getElementById(ifr_id);
// Apply the property "contentWindow" to myIFrame object
// In this way we get the iframe content
var content = myIFrame.contentWindow.document.body.innerHTML;
alert("Content: \n" + content); // Displays an Alert with the data from iframe
// Define a new text that will replace the content of the iframe
content = '<font color="blue">Text added with Javascript, from the main page</font>';
// Modify the iframe content
myIFrame.contentWindow.document.body.innerHTML = content;
}

Show/Hide javascript query

I made this html test website to test show/hide javascript.
When I load the page, I would like to show the first page but in my website everything is hidden 'till I click on a button'.
<html>
<head><title>Test</title>
<script>
function toggle(target){
var artz = document.getElementsByClassName('article');
var targ = document.getElementById(target);
var isVis = targ.style.display=='block';
for(var i=0;i<artz.length;i++){
artz[i].style.display = 'none';
}
targ.style.display = isVis?'none':'block';
return false;
}
</script>
</head>
<body>
About Us
Contact
Products
<div class="article" id="about" style="display:none;">ABOUT PAGE...</div>
<div class="article" id="contact" style="display:none;">CONTACT PAGE...</div>
<div class="article" id="products" style="display:none;">PRODUCTS PAGE...</div>
</body>
</html>
Well, that's because all your elements are hidden and the toggle-function is only invoked on click.
Use this:
window.onload = function(){
toggle('about'); //or whichever page you'd like to show on startup
}
This function is invoked on page-load and calls the toggle-function, providing the content that shoud be shown.
Alternatively, you could just change your style="display:none;" to style="display:block;" in the HTML for the content that should be shown on page-load.

Categories