What's wrong with this simple jQuery hover and replace HTML function - javascript

var originalContentFirst = $('#first').html();
$('#first').hover(function() {
$('#first').html('<strong>New HTML</strong>');
}, function() {
$('#first').html(originalContentFirst);
});
var originalContentSecond = $('#second').html();
$('#second').hover(function() {
$('#second').html('<strong>New HTML</strong>');
}, function() {
$('#second').html(originalContentSecond);
});
var originalContentThird = $('#third').html();
$('#third').hover(function() {
$('#third').html('<strong>New HTML</strong>');
}, function() {
$('#third').html(originalContentThird);
});
var originalContentFourth = $('#fourth').html();
$('#fourth').hover(function() {
$('#fourth').html('<strong>New HTML</strong>');
}, function() {
$('#fourth').html(originalContentFourth);
});
This was copied and adapted from elsewhere on this website. As you can see, its function is pretty basic. I have 4 divs (terrible ids, I know), and on a hover it should replace the HTML in them with the new HTML. Any idea why this is not doing anything at all? I'm sure I'm missing something rather elementary, but I can't figure out what the hell it is?
Edit: full HTML
<!DOCTYPE html>
<html>
<head>
<title>Bio</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css"/>
<link href='https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300' rel='stylesheet' type='text/css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script language="Javascript" type="text/javascript" src="script.js"></script>
</head>
<body>
<div id=first>
<span>About Me</span>
</div>
<div id=second>
<span>Past Jobs</span>
</div>
<div id=third>
<span>Projects</span>
</div>
<div id=fourth>
<span>About</span>
</div>
</body>
</html>

As Jaromanda X said - you're loading the script ABOVE the html, therefore it has nothing to attach to.
$(function() { // this waits until all html loaded
var originalContentFirst = $('#first').html();
$('#first').hover(function() {
$('#first').html('<strong>New HTML</strong>');
}, function() {
$('#first').html(originalContentFirst);
});
var originalContentSecond = $('#second').html();
$('#second').hover(function() {
$('#second').html('<strong>New HTML</strong>');
}, function() {
$('#second').html(originalContentSecond);
});
var originalContentThird = $('#third').html();
$('#third').hover(function() {
$('#third').html('<strong>New HTML</strong>');
}, function() {
$('#third').html(originalContentThird);
});
var originalContentFourth = $('#fourth').html();
$('#fourth').hover(function() {
$('#fourth').html('<strong>New HTML</strong>');
}, function() {
$('#fourth').html(originalContentFourth);
});
}); // this closes it

Related

Using Timber Framework counter with a URL API that continuously counts up

My skills with jquery and such are limited when it comes to this. For our website we are using timber framework with some of the plugins. I would like to use their counter but have the counter go up in real time. Please help if you can. Thank you in advance. in the HTML i have wrote realtime where i would like the counter to be realtime. I hope i have provided enough information. So in summary what i need help with is i would like to use the timber framework style and look but have the counter be realtime instead of stopping at a number and being a very basic counter.
HTML
`
<div class="column width-4 offset-4 center">
<div class="counter-wrapper">
<p style="font-size:60px;" class="counter lead"><span class="stats-1" data-count-from="1300000" data-count-to="realtime" >1000000</span></p>
<p style="font-size:36px;" class="lead">Hotspots</p>
</div>
</div>
`
Javascript
<script>
$( document ).ready( function(){
$( '.stats-1' ).counter();
$( '.stats-2' ).counter({
autoStart: true
});
});
</script>
Realtime counter URL
https://reelsonar-services.com/api/v1/hotspot_count
OUR COUNTER from a sample site
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery.flipcountdown.js"></script>
<link rel="stylesheet" type="text/css" href="jquery.flipcountdown.css" />
<script>
var hotspot_count = 1000000;
function fetch_waterbody_count() {
var url="https://reelsonar-services.com/api/v1/hotspot_count";
//var url="http://reelsonar-services.com:8085/hotspot_count";
var html = [];
$.getJSON( url, function( data ) {
console.log( data );
$.each(data, function(index, d){
html.push("Hotspots: ", d.hotspot_count, "<br>");
var count = parseInt( d.hotspot_count );
if( count != hotspot_count) {
hotspot_count = count;
update_counter( hotspot_count )
}
});
});
}
function update_counter( count ) {
jQuery('#flipcountdown').flipcountdown({size:'md',tick:count});
}
function reset_counter( count ) {
jQuery('#flipcountdown').flipcountdown({size:'md',tick:count});
}
function pulse_hotspot() {
(function pulse(back) {
$('#hotspot_img').animate(
{
'font-size': (back) ? '25px' : '35px',
opacity: (back) ? 1 : 0.5
}, 1200, function(){pulse(!back)});
$('#hotspot_img img').animate(
{
'width': (back) ? '125px' : '112px'
}, 1200);
})(false);
}
</script>
<body style="background: lightblue;text-align: center">
<script>
$(document).ready(function(){
$("#fetchButton").click(function(event){
fetch_waterbody_count();
});
$("#addOneButton").click(function(event){
hotspot_count += 1;
update_counter( hotspot_count );
});
$("#addTenButton").click(function(event){
hotspot_count += 10;
update_counter( hotspot_count );
});
$("#resetButton").click(function(event){
reset_counter(1000000);
});
setInterval(fetch_waterbody_count, 2000);
pulse_hotspot();
});
</script>
<script>
jQuery(function(){
jQuery('#flipcountdown').flipcountdown({size:'md',tick:hotspot_count}); <!-- Medium sized -->
})
</script>
<div style="font-size: x-large; padding-bottom: 1em">ReelSonar Global Hotspot Counter</div>
<div style="font-size: large; padding-bottom: 1em">Displays Hotspots as they are created by our users in real time.</div>
<pre>(Retrieves Hotspot count every two seconds)</pre>
<div id="hotspot_img"><img src="hotspot.png" /></div>
</body>
</html>
This is a polling issue: send Ajax request periodically, get the latest number and display it on screen (using Timber's counter to add animation effect).
Here is a working example. Please note it is a bit complex because the returned data is an array, not a single object (need to handle the situation when multiple numbers are returned in one array):
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="lib/css/components/timber.css" />
</head>
<body>
<span data-count-from="1" data-count-to="1" id="counter"></span>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="lib/js/plugins/jquery.tm.counter.js"></script>
<script type="text/javascript">
$(function() {
var queue = [];
var url="https://reelsonar-services.com/api/v1/hotspot_count";
var counter = document.getElementById('counter');
var $counter = $(counter);
var latestNum = null;
getData(true);
setInterval(function() {
getData();
}, 30000);
function getData(init) {
$.getJSON(url, function(data) {
if (init) {
var num = data.shift().hotspot_count;
counter.dataset.countFrom = num;
$counter.text(formatNumber(num));
}
queue = queue.concat(data);
playCount();
});
}
function playCount() {
if (queue.length === 0) {
return;
}
var countTo = queue.shift().hotspot_count;
if (countTo && countTo === latestNum) {
playCount();
}
latestNum = countTo;
counter.dataset.countTo = countTo;
$counter.counter();
setTimeout(function() {
counter.dataset.countFrom = countTo;
if (queue.length > 0) {
playCount();
}
}, 1000);
}
function formatNumber( number ) {
return number.toString().replace( /(\d)(?=(\d{3})+$)/g, '$1,' );
}
});
</script>
</body>
</html>

Dojo - hello world - using CDN module - get it work

When reading the introduction of Dojo, I followed (as newbie) the hello world tutorial.
How can I get this local demo working (via the CDN approach)? Afer a POC I will put it on a webserver, etc.
Step 1: I copied the module into the demo folder:
define([
'dojo/dom'
], function(dom){
var oldText = {};
return {
setText: function (id, text) {
var node = dom.byId(id);
oldText[id] = node.innerHTML;
node.innerHTML = text;
},
restoreText: function (id) {
var node = dom.byId(id);
node.innerHTML = oldText[id];
delete oldText[id];
}
};
});
Then in the current folder I put the Html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Tutorial: Hello Dojo!</title>
</head>
<body>
<h1 id="greeting">Hello</h1>
<script>
var dojoConfig = {
async: true,
packages: [{
name: "demo",
location: location.pathname.replace(/\/[^/]*$/, '') + '/demo'
}]
};
</script>
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"></script>
<script>
require([
'demo/myModule'
], function (myModule) {
myModule.setText('greeting', 'Hello Dojo!');
setTimeout(function () {
myModule.restoreText('greeting');
}, 3000);
});
</script>
</body>
</html>
When double clicking the browser on the Html file, no traffic is seen, no demo text is changed and re-changed.
It was not simple as a newbie to get the Dojo "hello world" running.
The changes are marked with ** ... **
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Tutorial: Hello Dojo!</title>
</head>
<body>
<h1 id="greeting">Hello</h1>
<script>
var dojoConfig = {
async: true,
packages: [{
name: "demo",
**location: 'K:/k_schijf/dojo/demo'**
}]
};
</script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"></script>
<script type="text/javascript">
require(
**[ "demo/myDojoModule.js" ],**
function (myDojoModule) {
myDojoModule.setText('greeting', 'Hello Dojo!');
setTimeout(function () {
myDojoModule.restoreText('greeting');
}, 3000);
});
</script>
</body>
</html>
Working "Hello World" example using CDN from Google.
var dojoConfig = {
async: true
};
require(["dijit/form/Button", "dojo/dom", "dojo/domReady!"], function(Button, dom){
// Create a button programmatically:
var myButton = new Button({
label: "Click me!",
onClick: function(){
// Do something:
dom.byId("result1").innerHTML += "Thank you! ";
}
}, "progButtonNode").startup();
});
<link href="https://ajax.googleapis.com/ajax/libs/dojo/1.10.0/dijit/themes/claro/claro.css" rel="stylesheet"/>
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"></script>
<button id="progButtonNode" type="button"></button>
<div id="result1"></div>

Can't make an onClick with Zepto

Hello I have a simple HTML page like this:
<html>
<head>
</head>
<body>
<h1>Test page</h1>
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript">
app.init([
"param", "123456789"
]);
app.execute();
app.edit();
</script>
</body>
</html>
The content of script.js is the following:
// Zepto include
...
// My code
var app = app || (function(){
var _args = {};
return {
init : function(Args) {
_args = Args;
},
execute : function() {
...
},
edit: function() {
$('body').on('click', function(e){
alert('aa');
});
},
};
}());
My problem is with this instruction $('body').on('click', function(e){.
I do not understand why.
It do not work.
Anyone to help me ?

Json Object to HTML table

I have a simple page with a "button/link" when i press the button i need to call the github api to return all issues logged in my repository and show in table format.
But when i hit the link nothing happends..
<html>
<head>
<script src="json-to-table.js"></script>
<script src="js/jquery-1.10.2.min.js"></script>
<script src="script.js"></script>
<script src="script.responsive.js"></script>
</head>
<body>
<h2>All Issues</h2>
VIEW
<div id="ghapidata" class="clearfix">
<script type="text/javascript">
$(function() {
$('#ghsubmitbtn').on('click', function(e) {
e.preventDefault();
$('#ghapidata').html('<div id="loader"><img src="css/loader.gif" alt="loader..."></div>');
var ghissues = 'https://api.github.com/repos/stroes/stroestest/issues';
requestJson(ghissues, function(json) {
if(json.message == "Not Found") {
$('#ghapidata').html("<h2>No Issues found in this repository</h2>");
}
else {
var jsonHtmlTable = ConvertJsonToTable(ghissues, 'jsonTable', null, 'Download');
}
}
}
});
</script>
</div>
</body>
</html>
Can anyone point me to where i have gone wrong with my code
your script is inside your div tag. When you change the html inside it, whole script will be removed. Try to place the script outside the div tag.
<html>
<head>
<script src="json-to-table.js"></script>
<script src="js/jquery-1.10.2.min.js"></script>
<script src="script.js"></script>
<script src="script.responsive.js"></script>
</head>
<body>
<h2>All Issues</h2>
VIEW
<div id="ghapidata" class="clearfix"></div>
<script type="text/javascript">
$(function() {
$('#ghsubmitbtn').on('click', function(e) {
e.preventDefault();
$('#ghapidata').html('<div id="loader"><img src="css/loader.gif" alt="loader..."></div>');
var ghissues = 'https://api.github.com/repos/stroes/stroestest/issues';
requestJson(ghissues, function(json) {
if(json.message == "Not Found") {
$('#ghapidata').html("<h2>No Issues found in this repository</h2>");
}
else {
var jsonHtmlTable = ConvertJsonToTable(ghissues, 'jsonTable', null, 'Download');
}
}
}
});
You should see errors in your console. You didn't close the functions right
$(function () {
$('#ghsubmitbtn').on('click', function (e) {
e.preventDefault();
$('#ghapidata').html('<div id="loader"><img src="css/loader.gif" alt="loader..."></div>');
var ghissues = 'https://api.github.com/repos/stroes/stroestest/issues';
requestJson(ghissues, function (json) {
if (json.message == "Not Found") {
$('#ghapidata').html("<h2>No Issues found in this repository</h2>");
} else {
var jsonHtmlTable = ConvertJsonToTable(ghissues, 'jsonTable', null, 'Download');
}
});
});
});
please look here again
var jsonHtmlTable = ConvertJsonToTable(ghissues, 'jsonTable', null, 'Download');
The second parameter requires id of your table you have no table with id jsonTable i think that is the problem

Handelbars.js: rendered HTML code not displayed

I new to Handelbars.js and I wanted to test it out. I just have one html file, whose content I want to be rendered by handlebars.js:
HTML file:
<html>
<head>
<script type="text/javascript">
console.log("Head:getting css");
</script>
<link rel="stylesheet" type="text/css" href="css/main_2.css">
</head>
<body>
<div class="phone-screen">
<script type="text/javascript">
console.log("Body:start MasterPage");
</script>
<!--MasterPage -->
<script id="app-bar" type="text/x-handlebars-template">
<div class="app-bar-container">
</div>
<div class="nav-bar-container">
<div class="nav-tab-left nav-tab-selected nav-tab-label-Selected">
<div class="tab-lable-centered ">History</div>
</div>
<div class="nav-tab-right nav-tab-notSelected ">
<div class="tab-lable-centered ">New</div>
</div>
</div>
</script
<!-- Content -->
<script id="workout-list-tpl" type="text/x-handlebars-template">
<div class="list-container">
<div class="week-seperator">
<div class="week-lable-right ">Week 12</div>
</div>
<div class="workout-card-white">
<div class="workout-card-label ">Workout</div>
</div>
</script>
<script type="text/javascript">
console.log("Body:getting Scripts________________________");
</script>
<script src="lib/handlebars.js"></script>
<script src="js/storage/memory-store.js"></script>
<script src="lib/jquery-1.8.2.min.js"></script>
<script src="js/MainView.js"></script>
<!--<script src="js/EmployeeView.js"></script>-->
<script src="js/main_2.js"></script>
</div>
</body>
The app javascript:
var app = {
initialize: function() {
console.log("initializer start: ");
var self = this;
//this.detailsURL = /^#employees\/(\d{1,})/;
//this.registerEvents();
this.store = new MemoryStore(function() {
self.route();
});
},
route: function() {
console.log("route function start.");
var self = this;
var hash = window.location.hash;
if (!hash) {
if (this.homePage) {
//this.slidePage(this.homePage);
} else {
console.log("homePage: ");
this.homePage = new MainView(this.store).render();
console.log("homePage = " + this.homePage );
//this.slidePage(this.homePage);
}
return;
}
var match = hash.match(this.detailsURL);
if (match) {
//this.store.findById(Number(match[1]), function(employee) {
//self.slidePage(new EmployeeView(employee).render());
//});
}
},
showAlert: function (message, title) {
if (navigator.notification) {
navigator.notification.alert(message, null, title, 'OK');
} else {
alert(title ? (title + ": " + message) : message);
}
},
};
console.log("app.initialize();");
app.initialize();
And the view.js:
var MainView = function(store) {
this.render = function() {
console.log("render function execution:" + MainView.template() );
this.el.html(MainView.template());
return this;
};
this.initialize = function() {
console.log("MainView init start.");
// Define a div wrapper for the view. The div wrapper is used to attach events.
this.el = $('<div/>');
//this.el.on('keyup', '.search-key', this.findByName);
};
this.initialize();
}
console.log("Handlebars.compile($(app-bar).html()); " );
MainView.template = Handlebars.compile($("#app-bar").html());
console log:
Head:getting css main_2.html:4
Body:start MasterPage main_2.html:12
Body:getting Scripts________________________ main_2.html:41
Handlebars.compile($(app-bar).html()); MainView.js:19
app.initialize(); main_2.js:46
initializer start: main_2.js:5
route function start. main_2.js:15
homePage: main_2.js:22
MainView init start. MainView.js:10
render function execution:
<div class="app-bar-container">
</div>
<div class="nav-bar-container">
<div class="nav-tab-left nav-tab-selected nav-tab-label-Selected">
<div class="tab-lable-centered ">History</div>
</div>
<div class="nav-tab-right nav-tab-notSelected ">
<div class="tab-lable-centered ">New</div>
</div>
</div>
MainView.js:4
homePage = [object Object]
The code goes through to the render function in view.js getting the html code but I do not know what happens next and hence why it is not rendered in the browser.
It seems I forgot the last step to append the generated html string to the html page:
$('body').append(page.el);

Categories

Resources