How to display JavaScript image with hyperlink inside a function - javascript

Programming and JavaScript noob here, so I appreciate all the help I can get. I'm using CometChat on my website and having some trouble working with their API's. I don't think it's a matter of the API's, it's more how to implement them. I pulled these lines of code from the CometChat website and more or less cut-n-pasted them into a user's profile page (I actually have a CMS system where I can implement this code on the fly). This bit of code goes on a user's profile page (user with ID number 160881).
<img src="http://www.wechsupport.com/content/images/chatwithme.png" alt="Click here to chat with me now">
<script type="text/javascript">
function checkstatus(data) {
if (data.s == 'available') {
alert('User is online');
}
}
window.onload = function() { jqcc.cometchat.getUser('160881','checkstatus')}; </script>
When navigating to the user's page, first an alert is displayed stating "User is online". Clicking OK, the alert disappears. Also, an image called CHATWITHME is displayed. That's fine, it works, but it's nasty. What I'd rather do is get rid of the alert all together and just display the CHATWITHME image/link if the user's status comes back as available (as shown in the function called CHECKSTATUS). I was thinking to simply take the A HREF piece and replace the ALERT with it such as this:
<script type="text/javascript">
function checkstatus(data) {
if (data.s == 'available') {
<img src="http://www.wechsupport.com/content/images/chatwithme.png" alt="Click here to chat with me now">;
}
}
window.onload = function() { jqcc.cometchat.getUser('160881','checkstatus')}; </script>
But this did not work. The alert went away (which is guess is good), but the image/link is not displayed. I have very limited experience working with code and simply don't know how to get the anchor tag to work within the function. I can use whatever help is offered.
Thanks!!!

You have to use Javascript setInterval() function to call the jqcc.cometchat.getUser method every X seconds. If you want to show/hide the button every time the status changes you also have to modify your HTML a bit:
<div id="chat-button">
<img src="http://www.wechsupport.com/content/images/chatwithme.png" alt="Click here to chat with me now">
</div>
And, in the checkstatus() function do something like:
function checkstatus() {
if (data.s == 'available') {
$('#chat-button').show();
} else {
$('#chat-button').hide();
}
}
(I'm using jQuery syntax in the Javascript code)

HTML
<div id="chatwithmebutton"></div>
JavaScript
function checkstatus(data) {
if (data.s == 'available') {
document.getElementById('chatwithmebutton').innerHTML = '<img src="http://www.wechsupport.com/content/images/chatwithme.png" alt="Click here to chat with me now">';
}
}

Thanks everyone. I created an "offline" button and uploaded it. Modified the code submitted by Walialu (thank you) slightly and came up with this:
<div id="chatonlinebutton"></div>
<div id="chatofflinebutton"></div>
<script type="text/javascript">
function checkstatus(data) {
if (data.s == 'available') {
document.getElementById('chatonlinebutton').innerHTML = '<img src="http://www.wechsupport.com/content/images/chatwithme.png" alt="Click here to chat with me now">';
} else {
document.getElementById('chatofflinebutton').innerHTML = '<img src="http://www.wechsupport.com/content/images/chatoffline.png" alt="User is offline right now">';
}
}
window.onload = function() { jqcc.cometchat.getUser('160881','checkstatus')}; </script>
If the user is online, the online button is displayed. If not, a simple graphic stating "User is offline" is displayed.
Thanks so much!!

Related

Clicking AJAX links? Watir

SOLVED:
I figured out my problem with this little piece of code:
b.link(id: 'm_wm_w5_m_lv_ctrl1_m_lnkWatch').fire_event :click
QUESTION:
I am having trouble clicking AJAX links with Watir.
Here is what I want to click.
https://i.imgur.com/Md4Rha3.png
This is what HTML looks like
<a id="m_wm_w5_m_lv_ctrl1_m_lnkWatch" href="javascript:__doPostBack('m_wm$w5$m_lv$ctrl1$m_lnkWatch','')"
style="white-space:nowrap; font-size:11px;">New Listing (160)</a></td>
So, in Watir, I used the following to click to think
b.link(id: 'm_wm_w5_m_lv_ctrl1_m_lnkWatch').click
But when I do that, I get this CSS pop up:
https://i.imgur.com/2DKWAhF.png
The HTML for close button on the pop up is:
<div id="NewsDetailDismissNew" class="btn mtx-btn-confirm enabled" title="Close">Close</div>
But when I use this in Watir
b.div(id: 'NewsDetailDismissNew').click
Nothing happens.
I did find some javascript that seems to correspond with the buttons
<!--<div class="container" >-->
<script>
var cvMarkAsRead=function( ){ return "Mark as Read"; };
</script>
<script>
var cvClose=function( ){ return "Close"; }; //This is closes the CSS pop up as far as I can tell
</script>
<script>
var cvOK=function( ){ return "OK"; };
</script>
<script>
var cvDismiss=function( ){ return "I've Read This"; };
</script>
<script>
var cvPreview=function( ){ return "Print Preview"; };
</script>
<!-- End NewsDetail modal -->
My question to you guys is
How can I click "New Listings" in Watir?
How can I click the "Close" button on the pop up?
I see that the link has some javascript, but I am not familiar enough with Watir to use b.execute_script successfully. I read the documentation. I am not understanding it and the examples provided are not similar enough to my problem for me to learn by practicing or copying.
Thank you in advance.
The piece of code below solves my problem. It clinks on New Listing and successfully loads all the new listings as well as avoids triggering that erroneous CSS pop up.
I think what this code does is activate the javascript by clicking the link.
I successfully clicked this link
<a id="m_wm_w5_m_lv_ctrl1_m_lnkWatch" href="javascript:__doPostBack('m_wm$w5$m_lv$ctrl1$m_lnkWatch','')"
style="white-space:nowrap; font-size:11px;">New Listing (160)</a>
By using this code in Watir:
b.link(id: 'm_wm_w5_m_lv_ctrl1_m_lnkWatch').fire_event :click

Stuck with onclick and document.GetElementById

I just began JavaScript and I've been stuck for a few hours now with an onclick which is not working, or maybe it's the document.getElementById. What I want to do is hide the div when I click on it.
If anyone can explain me what I'm doing wrong I would be grateful!
function closing() {
var closecook = document.getElementById("cookies");
closecook.style.display = "none";
}
#cookies{
display: block;
}
<div id="cookies" onclick="closing()">
Our website is using cookies, click here to close this message.
</div>
Here's my relevant HTML markup:
<body>
<div id="cookies" onclick="closing()">
Our website is using cookies, click here to close this message.
</div>
</body>
<script type="text/javascript" src="functions.js"></script>
Thanks.
Place your "script" block at the end of your body, not outside of it!
alter you the function "closing" to something like this:
function closing() {
var closecook = document.getElementById("cookies");
console.log(closecook);
closecook.style.display = "none";
}
In your browser: open the console by hitting "F12" or right-click anywhere in your browser and select "inspect element" then choose "console".
Now execute your function by clicking on the div.
If you see a "null" in the console: the problem comes from "document.getElementById("");".
If you do not see anything pop up in the console, your javascript file is not loaded properly. Make sure there is no typo in the file name! (Linux is case-sensitiv!).

Make duplicate html document with autogenerated name

Essetially, I am building a very rudimentary website builder that uses forms on a page to manipulate the HTML of the page,displayed below the input boxes, which eventually the user can get the source of to put onto their own website. I have not built it yet, but I was thinking that I would need more than one template in case anyone was trying to edit the same template at the same time, and having their edits overridden by others using the program. Here is a mockup for your leisure:
Html Displayed below input:
<h1 class="heading">Hi guys!</hi>
Form mockup:
<input id="headingEdit">
<script>
document.getElementById("heading").innerHTML = document.getElementById("headingEdit").value;
</script>
My problem is one that may or may not be relevant, and that is that should someone want to edit this template, when someone else is also editing it, then surely the html would keep on getting overridden by each other, and no-one would get anywhere. What I therefore want to do is be able to, when a user clicks on the 'Edit this Template' button on the homepage, they are taken to a randomly generated page, which is an exact duplicate of a master page, make their edits, and then that page is deleted, or (when I add integration) stored in a users account.
This might be a duplicate question, but the answer has not come up in my research so far.
Thanks in advance.
you can use AngularJS
http://www.w3schools.com/angular/default.asp
<!DOCTYPE html>
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="">
<p>Input something in the input box:</p>
<p>Name : <input type="text" ng-model="name" placeholder="Enter name here"></p>
<h1>Hello {{name}}</h1>
</div>
</body>
</html>
Here's a short PHP solution
$pageid = uniqid();
copy('template.html', $pageid . '.html');
print "Editable page is at: " .$pageid . ".html";
Add this somewhere in the template.html:
<?php
if (str_replace(' ', '', preg_replace('/\.html/', '', basename($_SERVER['PHP_SELF']))) !== 'template') {
print "<script>
var elems = document.getElementsByTagName('*'),
i;
for (i = 0; i < elems.length; i += 1) {
elems[i].setAttribute('contentEditable', 'true');
}
window.onbeforeunload = function(){
var a = new XMLHttpRequest() || new ActiveXObject('Microsoft.XMLHTTP');
a.onreadystatechange = function (b) {
if(a.readyState==4&&a.status==200){
}
}
xmlhttp.open('POST','remove_template.php',true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send('id=" . str_replace(' ', '', preg_replace('/\.html/', '', basename($_SERVER['PHP_SELF']))) . "');
}
//Custom JavaScript goes here
</script>";
}
?>
Then remove_template.php is:
if ($_POST['id'] != 'template' && ctype_alnum($_POST['id'])) {
unset($_POST['id']);
}
You should obviously change what urls to your needs, also remove_template.php is kinda insecure. I haven't tested this yet. If you ever add a user system. Made the $pageid link to their user account. Then just pass an if to not add the window.onbreforeunload
If you can't support PHP you can use an icky JavaScript solution
window.editPage () { document.body.contentEditable='true'; document.designMode='on'; }
window.savePage () { localStorage.setItem('savedPage', document.body.innerHTML); }
window.getPage () { document.body.innerHTML = localStorage.getItem('savedPage'); }
Then you can add the function to the onclick attribute
<div onclick="window.editPage()">Edit Page</div>
I've found something called Surreal CMS (Content Management System) which might be what you want. Or maybe something like create.js

How to show a "Saved!" message after Redirect() is made..?

I am currently working in a MVC4 project.
Imagine the following scenario:
(1) The user is allowed to add data to multiple tables and after that needs to confirm by hitting the Submit. <input type="submit" value="" id="saveBtn" title="Save" /> The reason there is no value is because I have CSS applied to the Submit.
(2) After that, to avoid a previous bug to prevent a refresh of the page to duplicate data, I need to Redirect the user in my Controller: return Redirect("Edit?Id=" + id);
(3) After the Redirect() is made, I want to show a simple message that says "Saved!" with a delay of 5 seconds. I do not want an alert("Saved!");.
I currently got a pseudo-solution working but not preferred. It's an simple click function in jQuery:
CSS
.successMessage {
color: darkgreen;
}
HTML
<div class="successMessage" style="display: none;">Saved!</div>
JS
$('#saveBtn').click(function () {
$(".successMessage").delay(500).show(0);
});
The problem is that, since I Redirect(); the user, my message cannot be delayed with this "solution". And after a Redirect(); is made, the message will not show up again.
What is a better approach in order to get a 'delayed' message? Thanks in advance.
Add a TempData in your submit action,and show the delay message in your view by confirm if TempData has value when page is ready.
Action:
//save info
TempData["Message"]="Saved!";
return Redirect("Edit?Id=" + id)
View:
string message=TempData["Message"]==null?"":TempData["Message"].ToString();
#if(message!="")
{
<div class="successMessage" style="display: none;">#message</div>
<script type='text/javascript'>
$(document).ready(function(){
$(".successMessage").delay(500).show(0);
})
</script>
}
The best solution to show notification messages is to use TempData["Message"] to store values and on every page do this-
if (TempData["Message"] != null)
{
ViewBag.Message = TempData["Message"];
}
Now in the View,
<div>
#if (ViewData["Message"] != null)
{
<div>Saved!</div>
}
</div>

Making a confirm box

I am trying to make my own dialog box. I want to use jquery for this. For some buttons on my site I need a confirmation dialog (like "Are you sure you want to delete" yes/no). When the dialog is active, the rest of the site should not be clickable.
So, I made this:
<div class="overlay" id="overlay" style="display:none;">
<div class="overlaycontent" id="overlaycontent">
<div id="overlaytext" class="overlaytext ">
<span id="overlaymessage" class="mediumtext bold">Deze klant verwijderen?</span>
<br><br>
<button id="nobutton" class="button1 highbutton hand" onclick="confirmno()">Nee</button>
<button id="yesbutton" class="button2 highbutton hand" onclick="confirmyes()">Ja</button>
</div>
</div>
</div>
ID overlay is over the whole page.
ID overlaycontent creates a white box on top of it.
ID overlaytext centers the message
ID overlaymessage contains the question/message.
ID nobutton is the button to say no :)
ID yesbutton is.. guess what :)
Now, the javascript to display a message:
function confirm(message,nobutton,yesbutton){
$('#overlaymessage').html(message);
$('#nobutton').html(nobutton);
$('#yesbutton').html(yesbutton);
$('#overlay').show();
}
function confirmno(){
$('#overlay').hide();
}
function confirmyes(){
????
}
So far, it works fine (except the yes button of course, please read further on), but for the next step I lack the knowledge. Say that I have a button somewhere to delete a user on my website.
<button class="redbutton" onclick="deleteuser(22)">
The button needs javascript like:
<script language="javascript">
function deleteuser(userid){
confirm('Delete user?','No','Yes');
??????
}
</script>
Now where the question marks are, I want the function to do something based on the fact the user clicked yes or no. How to catch this? I don't have any idea. Please help me out. I don't want to use Jquireui.dialog.
The trouble here is that you can't pause execution in javascript, so you'll need to adjust your confirm function (which you should probably rename, by the way, since JS has a native confirm function). Get rid of the onclick of your yes button, and adjust your confirm function like so:
function confirm(message,nobutton,yesbutton,yesfunction){
$('#overlaymessage').html(message);
$('#nobutton').html(nobutton);
$('#yesbutton').html(yesbutton);
$('#overlay').show();
$('#yesbutton').off("click").click(yesfunction);
}
Then, pass a function into your confirm call:
function deleteuser(userid){
function deleteConfirmed() {
// delete code here
}
confirm('Delete user?','No','Yes',deleteConfirmed);
}
You need to capture the result from your confirm dialogue box e.g.
var x = confirm("Are you sure you are ok?");
if (x) {
alert("Good!");
} else {
alert("Too bad");
}
You can simply do this.
<script language="javascript">
function deleteuser(userid){
if(confirm('Delete user?')) {
//'Ok' is clicked
}
else {
//'Cancel' is clicked
}
}
</script>

Categories