Ok, first off. No jquery, no ajax, just pure javascript.
I have the following code on a page called text.html.
<html><body>
<script>
function live(ID,txt2) {
var a = document.getElementById(ID);
a.innerHTML = (txt2);
}
setInterval(live, 250);
a.innerHTML =(txt2);
</script>
<div id="txt1">Live</div><p />
</body></html>
I have the following code on live2.html
<html>
<body>
<p />
<iframe width="400" height="50" src="text.html" name="frameA" id="frameA"></iframe><p />
<input type="button" value="Live" onClick="document.getElementById('frameA').contentWindow.live('txt1','L I V E')">
<input type="button" value="Rebroadcast" onClick="document.getElementById('frameA').contentWindow.live('txt1','Rebroadcast')"><br />
text
</body>
</html>
The current code works exactly as I wanted it to by updating the information in an iframe. My issue is this. If someone visits text.html directly, I want them to be able to see whatever I've changed that document to.
Example:
I click on a button and the text in the iframe now says rebroadcast.
Someone else visits text.html and they also see rebroadcast. If while they are looking at text.html, I hit the live button, the text.html page will update with the word live.
I can do PHP scripting on this as well. I have tried jquery and have issues with getting it to work correctly and I don't really have the knowledge or access to implement much of anything else.
This is an on-going project. The end result, I hope, will be an iframe that I can update while not actually being on the same page that the frame is located on. (same domain tho) The content will be anything from images, to youtube embeds and pictures. I'm trying to get a more comprehensive idea of how this language works and that's why I'm taking it one step at a time. I have no issue with visiting tutorials or looking at pre-made solutions. Thanks for your help. :)
I think I'm probably missing something. Users will always see the text "Live" because that's what's hard-coded in text.html. It doesn't matter if you change the text through JavaScript since it will only affect the browser that you're seeing. You need to save it to a persistence storage (ie. database) and dynamically display it on the page.
live2.html can use AJAX to send the changes to the server, which can then update live.html. But this is a poor way to do it, since it means that the contents of live.html are updated outside of your version control and/or content management system. It's better to use a real database and generate the page dynamically, as suke said.
First off this is what happens when someone learning programming languages doesn't fully comprehend what a language can and can't do. The original idea was to let a specific group of people know when it was a re-broadcast or when the show was live. I wanted the control of when to change that information to only be available to an admin of sorts. In the end the entire idea got scrapped and entirely impractical. The solution, essentially, doesn't exist in the context of the way I wanted to accomplish this. Years later...
The solution is to have live and rebroadcast inside div tags with CSS. Then use a JavaScript function to change the attributes of the divs to either be hidden or shown. The button or or link would need to exist on the same page as the live or rebroadcast text. This would also mean that there is no need for a separate frame. To have this element controlled from outside the page it's on could only be done by storing a value somewhere else and having that value periodically checked.
JSFiddle
The Script:
var x = document.getElementById("txt1");
var y = document.getElementById("txt2");
function htext() {
x.style.visibility = 'visible';
y.style.visibility = 'hidden';
}
function stext() {
x.style.visibility = 'hidden';
y.style.visibility = 'visible';
}
function ctext() {
var z = getComputedStyle(x).getPropertyValue("visibility");
if (z != 'hidden') {
stext();
} else if (z != 'visible') {
htext();
}
}
The CSS:
#txt1 {
visibility: hidden;
margin-left:0px;
}
#txt2 {
visibility:visible;
margin-left:0px;
}
The HTML:
<span id="txt1">Live</span>
<span id="txt2">Rebroadcast</span>
<br />
click
To be honest. I'm not entirely sure of the programming needed to store information somewhere else and have a check to see if certain conditions are true. The program above will essentially hide and show a div. I could probably go a step further and use JQuery to create and remove the actual div itself. In the end this is essentially close to the solution I ended up using and then later on discarding and giving up on the project.
Related
I'm studying webdevelopment and I'm doing a single page application right now. We are using JavaScript, and I can`t use jquery, bootstrap, etc. I have googled, seen the videos from the lectures, but I am still blank as a canvas.
The problem is I need to make a contactregistre. You should be able to click on the contacts, a different section of the page should be made active where you will be able to edit the contacts and see where they live. The map is OK, but I don`t know how I can make this happen, I find no examples about this which does not suggest using jquery.
We have guessed something like this, but it is probably wrong:
document.querySelector("tr").addEventListener('click' , e => {
document.querySelector('editContact')
function editContact(contact) {
let editContact = document.querySelector("#searchcontact tr");
editContact.innerHTML = "TR";
let form = document.editContact()
}
})
Thanks so much in advance!
There are numerous ways to do this. This is not a complete solution, but should get you started:
Typically you'd have a text input already in your table <input name="username_1" class="hidden" type="text">, which is hidden, along side the content, like <span id="username_1">MAREN</span>
Then you'd have some CSS to hid things:
.hidden {
display:none;
}
So on the click even you'd add the hidden classname to the SPAN and remove it from the INPUT. This visually swaps the static value for the label.
There's more to it after that, but give it a try.
This may have been answered elsewhere but I couldn't find a question which fit my circumstances.
I have a site page which out puts in DIVs records from a database, this the same DIV looped. In this DIV I have a button which brings up a modal box. This modal DIV however is not coded within the looped DIV.
I need the modal box to be able to get the ID of the record for the data which the looped DIV is showing.
The button is:
<a href = "javascript:void(0)"onclick = "document.getElementById('light2').style.display='block';document.getElementById('fade').style.display='block'">
<div class= "obutton feature2">Reserve Book</div>
</a>
I assume I'll need to use java script somehow, but I don't know how to use it in this manner.
Ideally using some sort of form $_POST would be easiest with the form button having the set value of the $row->ID, but I can't make a form button also a can I?
Sorry for the possibly silly question, as I've said I've found similar things asked, but always find it hard to understand the full workings on other peoples scenarios as opposed to my own.
All help appreciated -Tom
I think the key to your answer is understanding how JS (and jQuery) uses this. When a function is called, the caller is almost always passed as the this variable. For example:
<button data-id="1234" onclick="runThisFunction()" value="run" />
<script>
function runThisFunction() {
//Do Stuff
var data_id = this.data('id');
};
</script>
In the above code, this contains the button that was clicked on. You can get lots of information from the this variable. In jQuery, you can even get to siblings, parents, or children in the DOM.
Here is an example solution to your question:
http://jsfiddle.net/yr6ds/1/
Here is a more elegant solution:
http://jsfiddle.net/yr6ds/2/
I am trying to enhance the menu of my website a bit by making use of the jQuery accordion plugin:
http://jqueryui.com/accordion/
This works perfectly fine and i think that it is a great plugin to make use of... However, i have noticed that it requires a specific layout in order to achieve these results:
<div id="accordion">
<h3>Section 1</h3>
<div>
<p>
ETC...
</p>
</div>
NB: repeated for every result
</div>
Now this is a bit of a problem in that when javascript is disabled, the entire output of this menu is displayed (all categories and containing information).
This is simply too much information to be output all at once and this is the reason that it has been broken up with PHP in the first place. In essence it would look like this:
// No category selected
* Fruits
* Vegetables
// Category selected
o Fruits
- Apples
- Oranges
* Vegetables
// Javascript Disabled
o Fruits
- Apples
- Oranges
* Vegetables
- Potatoes
- Onions
So what i would like to do, is provide an alternate means of navigation for users that have disabled javascript (the old menu that is fully functional and works regardless).
I currently make use of a few options in modernizer:
http://modernizr.com/
To increase browser support on some CSS properties i have used. I am aware that it can be used to detect if javascript is enabled by appending a class "js" to the body tag.
So with that, i decided to try and wrap the old menu within a containing div, and the new menu within a containing div. My idea is that i can then these divs with display: none;.
Before i carry on, i am really just guessing here so if i am going about this the wrong way... I would appreciate it if someone could point me in the right direction. With that out of the way, i found an article on stackoverflow that relates to this:
PHP & <noscript> combination to detect enabled JavaScript in browser
And with my very limited knowledge of jQuery have adapted it slightly to fit what i hope to achieve:
<script type="text/javascript">
$(document).ready(function(){ // Use jQuery!
// Remove the no-js and add the js (because JS is enabled (were using it!!)
$("body").removeClass("no-js").addClass("js");
})
// Put it in a var so you dont traverse the DOM unnecessarily.
var useJS = $("body").hasClass("js");
if(useJS){ // true or false if <body> has class JS.
// JS Enabled
$("#oldMenu").css("display", "none");
$("#newMenu").css("display", "inline");
} else {
// JS NOT enabled
$("#newMenu").css("display", "none");
$("#oldMenu").css("display", "inline");
}
</script>
Now the problem I am facing is that i cannot seem to get this script to register or make any visible difference. When i look at the body tag in the source there is no class on the body tag. The menu is not triggering as i thought it would and i am now after quite some time... Very confused.
If anyone could offer me some assistance, advice, information or indication that would help me to solve this current issue, i would really, REALLY appreciate that!
Thank you for taking the time to read through my line story! :)
EDIT:
#RomainPaulus suggested this and it works:
<script type="text/javascript">
$(document).ready(function(){ // Use jQuery!
// Remove the no-js and add the js (because JS is enabled (were using it!!)
$("body").removeClass("no-js").addClass("js");
// Put it in a var so you dont traverse the DOM unnecessarily.
var useJS = $("body").hasClass("js");
if(useJS){ // true or false if <body> has class JS.
// JS Enabled
$("#oldMenu").css("display", "none");
$("#newMenu").css("display", "inline");
} else {
// JS NOT enabled
$("#newMenu").css("display", "none");
$("#oldMenu").css("display", "inline");
}
})
</script>
Kenneth's response explains a lot, but I have noticed something else. Your code
var useJS = $("body").hasClass("js");
is executed before
$(document).ready(function(){ // Use jQuery!
// Remove the no-js and add the js (because JS is enabled (were using it!!)
$("body").removeClass("no-js").addClass("js");
})
You should put everything inside the $(document).ready(function(){ ... })
So I guess that explains why your code doesn't work.
The problem you face here is that, obviously when Javascript is not enabled, you're Javascript is not executing.
What you need to is hide the DIV by default with CSS. Then, when your page loads, show it through JS.
Javascript disabled => Div stays hidden, because no code is executed
Javascript enabled => div is hidden on load, but the script shows it
Also, if Javascript is disabled, Modernizr won't help, since it's a JavaScript library.
i have a javascript prompt like the following and i would like to bring the prompt center of the screen. How to do this in using javascript?
function showUpdate() {
var x;
var name=prompt("Please enter your name","");
if ( name != null ) {
x="Hello " + name + "! How are you today?";
alert("Input : " + name );
}
}
And this is how i call this :
<a onclick = "showUpdate() " style="vertical-align: middle;" class="parent" href=""><span>5. Missed P/U Comments</span></a>
it works find excepts the prompt goes to the left corner in IE and center in Firefox
but i need to the same solution to work in both the browsers.
The prompt (and alert) popups are implemented differently depending on the browser you're using. This is because the popups are browser functionalities, they aren't JavaScript objects or anything like that. (Just like the console is different for each browser, it depends on the implementation.)
If you really want your prompts to be positioned / styled consistently, you're going to have to build your own prompt.
The easy way out would be to use a library like jQueryUI.
On the other hand, you can just build it yourself:
document.getElementById('showPromptButton').addEventListener('click', showSprompt);
document.getElementById('promptButton').addEventListener('click', submitPrompt);
var prompt = document.getElementById('myPrompt');
var promptAnswer = document.getElementById('promptAnswer');
function showSprompt() {
promptAnswer.value = ''; // Reset the prompt's answer
document.getElementById('promptQuestion').innerText = "What's your question?"; // set the prompt's question
prompt.style.display = 'block'; // Show the prompt
}
function submitPrompt() {
var answer = promptAnswer.value; // Get the answer
prompt.style.display = 'none'; // Hide the prompt
console.log(answer);
}
#myPrompt{
display:none;
/* Style your prompt here. */
}
<input id="showPromptButton" type="button" value="Show Prompt" />
<div id="myPrompt" class="proptDiv">
<span id="promptQuestion"></span>
<input id="promptAnswer" type="text" />
<input id="promptButton" type="button" value="Submit" />
</div>
You cannot customize or postion the default javascript prompt. Check this SO answer for workarounds.
How to customize the JavaScript prompt?
Prompts, alerts, and confirms are basic functions that each browser has its own way of displaying to the user. There's really no reason that you should want to customize these functions, either.
If you really want advanced functionality and complete customization, you'll have to make your own custom alert. You can do this in one of several ways. One out of two options that I'll suggest is creating two divs (one that fades out the rest of the page and one that appears like an alert) in Javascript and use those as a pseudo-prompt. The second is to create a new window, remove a lot of its functionality and change some HTML on the newly opened page to make it look somewhat like an alert.
I feel like the last one is really overdoing it though. If you want a prompt, they're ugly... Otherwise, you'll need to make something yourself with a positioned div and faded background.
...but i need to the same solution to work in both the browsers.
prompt (and its cousin alert) are very outdated. You have no control over their appearance or position. It's mostly best to avoid them.
Instead, you can do a popup message using an absolutely-positioned div (or any other block element), which not only gives you full control over its position, but full styling as well. If you look around, you'll find dozens of examples of doing this, and toolkits for it, there's no need to roll your own unless you really want to.
Regardless which way you end up doing it, your logic using it will have to change, because prompt is synchronous (all script on the page comes to a screeching halt and waits for the prompt), whereas modern ways of doing this are asynchronous (event-oriented). So for instance, your new code for using the popup might look like this:
function showUpdate() {
popup("Please enter your name","", function(name) {
if (name!=null)
{
x="Hello " + name + "! How are you today?";
alert("Input : "+name); // <== I left this one alone, looks like debugging
}
});
}
NOTE: The method window.showModalDialog() is obsolete and is not
supported in modern browsers. Please do not use it.
You cannot reposition window.alert(), but you can do so with window.showModalDialog() as described in this page: http://bytes.com/topic/javascript/answers/849283-change-position-alert-possible
https://developer.mozilla.org/en-US/docs/DOM/window.showModalDialog
I have a pretty specific scenario where I would like to select all elements with jQuery, make a CSS change, save the elements, then reverse the change I made.
The Goal
I created a jQuery plugin called jQuery.sendFeedback. This plugin allows the user to highlight areas of the screen, as shown in this demo. When they submit their feedback the plugin grabs all the HTML on the page and dumps it into a callback function. Like so:
$('*').each(function ()
{
$(this).width($(this).width());
$(this).height($(this).height());
});
var feedbackInformation = {
subject: $feedbackSubject.val(),
details: $feedbackDetails.val(),
html: '<html>' + $('html').html() + '</html>'
};
if (settings.feedbackSent)
settings.feedbackSent(feedbackInformation);
The callback function accepts this feedback information and makes an AJAX call to store the page HTML on the server (this HTML includes the red box highlights the user drew on the screen). When someone from tech support needs to view the user's "screen shot" they navigate to a page that serves up the stored HTML so the developer can see where the user drew their highlights on the screen.
My original problem was that different screen resolutions made the elements different sizes and the red highlights would highlight the wrong areas as the screen changed. This was fixed pretty easily by selecting all elements on the page and manually setting their height and width to their current height and width when the user takes the snap shot. This makes all the element sizes static, which is perfect.
$('*').each(function ()
{
$(this).width($(this).width());
$(this).height($(this).height());
});
The Problem
The issue with this is that when the plugin is done transmitting this HTML the page currently being viewed now has static heights and widths on every element. This prevents dropdown menus and some other things from operating as they should. I cannot think of an easy way to reverse the change I made to the DOM without refreshing the page (which may very well end up being my only option). I'd prefer not to refresh the page.
Attempted Solution
What I need is a way to manipulate the HTML that I'm sending to the server, but not the DOM. I tried to change the above code to pull out the HTML first, then do the operation on the string containing the HTML (thus not affecting the DOM), but I'm not quite sure what I'm doing here.
var html = '<html>' + $('html').html() + '</html>';
$('*', html).each(function ()
{
$(this).width($(this).width());
$(this).height($(this).height());
});
This did not work. So either I need to be able to manipulate the string of HTML or I need to be able to manipulate the DOM and undo the manipulation afterward. I'm not quite sure what to do here.
Update
I employed the solution that I posted below it is working beautifully now. Now I am wondering if there is a way to statically write all the css for each element to the element, eliminating the need for style sheets to be referenced.
I think you are mostly on the right track by trying to make the modifications to the HTML as a string rather than on the current page for the user.
If you check this post, you might also want to follow the recommendation of creating a temporary <div> on the page, cloning your intended content to the new <div> ensuring it is invisible using "display:none." By also putting a custom Id on the new <div> you can safely apply your static sizing CSS to those elements using more careful selectors. Once you have sent the content to the server, you can blow away the new <div> completely.
Maybe?
After much pain and suffering I figured a crude but effective method for reverting my modifications to the DOM. Though I hadn't gotten around to trying #fdfrye's suggestion of cloning, I will be trying that next to see if there is a mroe elegant solution. In the meantime, here is the new code in case anyone else can benefit from it:
$('*').each(function () {
if ($(this).attr('style'))
$(this).data('oldStyle', $(this).attr('style'));
else
$(this).data('oldStyle', 'none');
$(this).width($(this).width());
$(this).height($(this).height());
});
var html = '<html>' + $('html').html() + '</html>';
$('*').each(function () {
if ($(this).data('oldStyle') != 'none')
$(this).attr('style', $(this).data('oldStyle'));
else
$(this).removeAttr('style');
});
When I'm looping through every element and modifying the css, I log the original value onto the element as data. After I assign the DOM HTML to a variable I then loop through all elements again and restore the style attribute to its original value. If there was no style attribute then I log 'none' to the element data and then remove the style attribute entirely when looping through again.
This is more performance heavy than I wish it was since it loops through all elements twice; it takes a few seconds to finish. Not horrible but it seems like a little much for such a small task. Anyway, it works. I get a string with fixed-sized HTML elements and the DOM goes back to normal as if the plugin never touched it.