Onclick function in img tag - javascript-events

I am trying to make an image clickable, that when we click on the image touchRock() function will be called and image changes accordingly.
Here is the code:
<tittle> iRock - The Virtual Pet </tittle>
<script type ="text/JavaScript">
function touchRock(){
var userName = prompt("What is ur userName??" , "Enter name here .");
if (userName != null){
alert("It is good to meet you " + userName + "."};
document.getElementId("rockImg").src="joker.jpg";
}
}
</script>
</head>
<body onload = "alert('hello, I am ur pet rock');">
<div style "margin-top:400px; text-align:center">
<img id="rockImg" src="irock.jpg" alt="iRock" style="cursor:pointer" onclick="touchRock();"/>
</div>
</body>
pls help me.

U shall use document.getElementById, not document.getElementId.
And U have syntax error in
alert("It is good to meet you " + userName + "."};
Try this:
<html>
<head>
<tittle> iRock - The Virtual Pet </tittle>
<script type ="text/JavaScript">
function touchRock(){
var userName = prompt("What is ur userName??" , "Enter name here .");
if (userName != null){
alert("It is good to meet you " + userName + ".");
document.getElementById("rockImg").src="joker.jpg";
}
}
</script>
</head>
<body onload="alert('hello, I am ur pet rock');">
<div style "margin-top:400px; text-align:center">
<img id="rockImg" src="irock.jpg" alt="iRock" style="cursor:pointer" onclick="touchRock();"/>
</div>
</body>
</html>

Related

Sort listview on button click in jQuery Mobile

I'm new to jQuery mobile. I want to be able to sort listview items by pricing (low-high, for example) when a button is clicked. I can't seem to find anything online on how to do it in jQuery mobile. I'm aware there's tiny sort plugin, but I need to write the method myself.
This is a sample of my listview.
<ul data-role="listview" data-filter="true" data-input="#searchpostcode" class="searchable">
<li class="british fish low-budget"><a href="#">
<img src="images/fishandchips.png" class="ui-li-thumb">
<h4>Fish and Chips</h4>
<p>British cuisine, contains fish</p>
<p class="ui-li-aside">£6.00</p>
</a>
</li>
<li class="spanish high-budget"><a href="#">
<img src="images/paella.png" class="ui-li-thumb">
<h4>Seafood Paella</h4>
<p>Spanish cuisine, contains seafood</p>
<p class="ui-li-aside">£8.00</p>
</a>
</li>
<li class="american medium-budget"><a href="#">
<img src="images/burger.png" class="ui-li-thumb">
<h4>Beef Burger</h4>
<p>American burger</p>
<p class="ui-li-aside">£7.00</p>
</a>
</li>
</ul>
Is there an easy way to do it? Any guidance will be appreciated, thanks.
Sorting the incoming data is the fastest option, there will be anyway a DOM manipulation. So, sort the data and then invoke listview("refresh").
DEMO:
var data = [
{category: "british fish low-budget", picture: "fishandchips", name: "Fish and Chips", description: "British cuisine, contains fish", price: "6.00"},
{category: "spanish high-budget", picture: "paella", name: "Seafood Paella", description: "Spanish cuisine, contains seafood", price: "8.00"},
{category: "american medium-budget", picture: "burger", name: "Beef Burger", description: "American burger", price: "7.00"}
];
function updateListview(sorting){
var direction = ~sorting.indexOf("-asc") ? 1 : -1;
data.sort(function(a, b) {
return direction *(Number(a.price) - Number(b.price));
});
var html = "";
$.each(data, function(index, item) {
html += '<li class="' + item.category + '"><a href="#">';
html += '<img src="images/' + item.picture + '".png" class="ui-li-thumb">';
html += '<h4>' + item.name + '</h4>';
html += '<p>' + item.description + '</p>';
html += '<p class="ui-li-aside">£' + item.price + '</p>';
html += '</a></li>';
});
$("#food").data("sort", sorting).empty().html(html).listview("refresh");
}
$(document).on("listviewcreate", "#food", function(event, ui) {
$("#price-sort").on("vclick", function(e) {
var sorting = $("#food").data("sort") == "price-asc" ? "price-desc" : "price-asc";
updateListview(sorting);
});
});
$(document).on("pagecreate", "#page-one", function() {
updateListview("none");
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.css">
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js"></script>
</head>
<body>
<div id="page-one" data-role="page">
<div role="main" class="ui-content">
<a id="price-sort" href="#" class="ui-btn ui-corner-all ui-icon-delete ui-btn-icon-left ui-mini">Sort by Price</a>
<ul data-role="listview" data-sort="none" data-inset="true" data-filter="true" id="food" name="food"></ul>
</div>
</div>
</body>
</html>
Moreover, if You need a more sophisticated sort function, which can sort by more than just one parameter, take a look here: Sort array of objects by string property value

AJAX (JSON) problems with NGRepeat

I've got problem with outputting my JSON from server (Node.js) to NGrepeat.
I have tried a lot and debugged with both Firebug and Firefox Web Inspector.
For some reason it will not show the data from the JSON, even then the JSON looks correct when I output it in the Firebug console (using Firefox 39.0).
JSON:
[{ nr:"1", svenska:"test2", spanska:"testo2"},{ nr:"2", svenska:"test3", spanska:"testo3"},{ nr:"3", svenska:"test4", spanska:"testo4"},{ nr:"4", svenska:"test5", spanska:"testo5"},{ nr:"5", svenska:"test6", spanska:"testo6"}]
Angular.js
/**
*
* The client Angular.JS main file for the project
*/
var glosorApp = angular.module('glosorApp',['directives']); /* */
angular.module('directives', [])
.directive('toggleClass', function () {
var directiveDefinitionObject = {
restrict: 'A',
template: '<div ng-click="localFunction()" ng-class="selected" ng-transclude></div>',
replace: false,
scope: {
model: '='
},
transclude: true,
link: function (scope, element, attrs) {
scope.localFunction = function () {
scope.model.value = scope.$id;
};
scope.$watch('model.value', function () {
if (scope.model.value === scope.$id) {
scope.selected = "active";
} else {
scope.selected = '';
}
});
}
};
return directiveDefinitionObject;
});
glosorApp.controller('listController', function ($scope, $http) {
$http.post(PROJEKT_SOKVAG+'/_myroute',
{type:AJAX.LISTA_GLOSOR_CLI_R}).success( function(data) {
console.log("Kommer hit lookdeep: "+lookdeep(data.data));
$scope.glosor = data.data;
// $scope.$apply();
console.log("Kommer hit lookdeep: $scope.glosor "+lookdeep($scope.glosor));
});
});
function ajaxanrop(callback, data_) {
$.ajax({
url: PROJEKT_SOKVAG+'_myroute',
type: 'POST',
dataType: 'json',
data: data_ , // the data that should be sent to server
success: function(data) { if ( callback ) callback(data); },
error: function() { if ( callback ) callback(null); },
complete: function() { /* console.log("Klart"); */ }
});
}
HTML (EJS template)
<!DOCTYPE html>
<html ng-app="glosorApp" ng-init="model = { value: 'dsf'}">
<head>
<title>Glosor</title>
<script type="text/javascript">
var PROJEKT_SOKVAG="<%=project_path %>", LoginUser="<%= user.username %>";
</script>
<script type="text/javascript" src="http://w42.se/webbroot/js/jquery-1.9.1.min.js"></script>
<script src="http://w42.se/<%=project_path %>/jquery-ui-1.js" type="text/javascript"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.js"></script>
<script type="text/javascript" src="http://w42.se<%=project_path %>/lookdeep.js"></script>
<script type="text/javascript" src="http://w42.se<%=project_path %>/constants.js"></script>
<script type="text/javascript" src="http://w42.se<%=project_path %>/clientAngular.js"></script>
</head>
<body>
<div id="vald_sida" style="display:none;" class="mentorer"></div>
<p>Användarnamn: <%= user.username %></p>
<p>Email: <%= user.email %></p>
<p>Log out</p>
<div id="wrapper" ng-controller="listController" >
<p>Lägg till Glosor</p>
<p>Testa Glosor</p>
<div class="clear"></div>
<div class="list">
<div class="filterarea">
<h4>Sökning</h4>
<div>
<span>Nr: <input ng-model="search.nr" ng-model-options="{debounce: 20000}"></span>
<span>Svenska: <input ng-model="search.svenska" ng-model-options="{debounce: 20000}"></span>
<span>Spanske: <input ng-model="search.spanska" ng-model-options="{debounce: 20000}"></span>
<span>Poäng: <input ng-model="search.poang" ng-model-options="{debounce: 20000}"></span>
</div>
</div>
<div class="pad clearfix">
<h4>Resultat</h4>
Välj: alla <input type="checkbox" ng-model="master"><br/>
<div ng-form="">
<div class="list">
<div class="thead">
<div>
<span class="sortable"><a href=""
ng-click="predicate = 'nr'; reverse=!reverse">#</a></span>
<span class="sortable td"><a href=""
ng-click="predicate = 'svenska'; reverse=!reverse">Svenska</a></span>
<span class="sortable td"><a href=""
ng-click="predicate = 'spanska'; reverse=!reverse">Spanska</a></span>
<span class="sortable td"><a href=""
ng-click="predicate = 'poang'; reverse=!reverse">Poäng</a></span>
</div>
</div>
<div class="tbody">
<div ng-repeat="glosa in filter_glosor = (glosor | orderBy:predicate:reverse | filter:search)">
<div class="tr" toggle-class="" model="model">
<span class="td">{{glosor.nr}}</span>
<span class="td">{{glosor.svenska}}</span>
<span class="td">{{glosor.spanska}}</span>
</body>
</html>
As for the ng-repeat issue, it looks like you're using a filter incorrectly. Try this:
<div ng-repeat="glosa in glosor | orderBy:predicate:reverse | filter:search">
NB If you're trying to GET data, you should use $http.get instead of the $http.post(PROJEKT_SOKVAG+'/_myroute', you have.
It will save confusion down the road when maintaining the app.
Well, I found the error that I made, and it was a ridiculously simple error. Quite embarrasing actually... ;-)
I put glosor.svenska instead of glosa.svenska in the repeated block (inside the NGRepeat).
That's the bad thing with having the array name and the element name too similar, you might mix them up.
This means that I put the array instead of the repeated single array element inside the repeated block.

google.maps.places.Autocomplete requests Location too many times in Firefox

in my website, I have a singn_up-form and use the Google-Api to give the user some suggestions. The API requests the location of the user once in Internet-Explorer. But if I try Firefox, the requests are looped until I click "Standort immer Freigeben" - it means "always accept".
function initialize() {
autocomplete = new google.maps.places.Autocomplete(
(document.getElementById('autocomplete')),
{ types: ['geocode'] });
}
The code is loaded at document.ready and contains more code, but this snippet also reproduces the error.
Does anyone has some ideas?
Try this :
put the apis in your <head></head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false&libraries=places"></script>
put this in your body tag:
<label for="autocomplete">Please Insert an address:</label>
<br>
<input id="autocomplete" type="text" size="100">
put this in your onload function:
var input = document.getElementById('autocomplete');
new google.maps.places.Autocomplete(input);
this is my code :
var input = document.getElementById('autocomplete');
new google.maps.places.Autocomplete(input);
<html>
<head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false&libraries=places"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<label for="autocomplete">Please Insert an address:</label><br>
<input id="autocomplete" type="text" size="100">
</body>
</html>
You might have kept some onfocus attribute as given in Google Maps API Example
<input id="autocomplete" placeholder="Enter your address" onFocus="geolocate()" type="text"></input>
OR
If you don't require keeping bounds for places suggestions, you may want to remove it
OR
If you need to set bounds for suggestions keep some condition to not call location consent every time, if user gives permission.
Please keep your condition in geolocate() function
Issue is happening only in Mozilla FireFox
What you want to do is this:
function handlePermission() {
navigator.permissions.query({name:'geolocation'}).then(function(result) {
if (result.state == 'granted') {
geoBtn.style.display = 'none';
} else if (result.state == 'prompt') {
geoBtn.style.display = 'none';
navigator.geolocation.getCurrentPosition(revealPosition,positionDenied,geoSettings);
} else if (result.state == 'denied') {
geoBtn.style.display = 'inline';
}
});
}
then put handlePermission(); after your callback function receives permission

Getting a response from Cfajaximport / ajax with coldfusion

I've searched a number of the previous responses, but none of them have helped me. I'm actually extrapolating on another script I found earlier.... but I'm not sure how to capture the response in AJAX. I was guessing that handleResponse would just capture whatever is outputted on checkdomain.cfm, but I can't seem to make that happen so I can output it. So in the example below, somehow the person who developed this script was able to get back AVAILABLE from checkdomain.cfm, but I can't figure out how to do that.
Thanks in advance!
<head>
...
<cfajaximport />
...
<script>
function handleResponse(s) {
if(s == "AVAILABLE") {
//rewrite span
var domainspan = document.getElementById('DomainStatus');
var newcontent = "Available To Register :)";
domainspan.innerHTML = newcontent;
var loadingspan = document.getElementById('frmGO');
var newcontent = "<input name='' value='GO!' class='search_domain_go' type='submit' />";
loadingspan.innerHTML = newcontent;
} else {
//rewrite span
var domainspan = document.getElementById('DomainStatus');
var newcontent = "Unavailable To Register :(";
domainspan.innerHTML = newcontent;
var loadingspan = document.getElementById('frmGO');
var newcontent = "<input name='' value='GO!' class='search_domain_go' type='submit' />";
loadingspan.innerHTML = newcontent;
}
}
function CheckDomain() {
var loadingspan = document.getElementById('frmGO');
var newcontent = "<input name='' type='image' class='search_domain_go' src='images/ajax-loader.gif' alt='' />";
loadingspan.innerHTML = newcontent;
ColdFusion.Ajax.submitForm('frmDomainCheck','checkdomain.cfm',handleResponse);
}
</script>
...
</head>
<body>
...
<div class="search_domain">
<div class="search_domain_form">
Search Your Domain Here<br />
<form method="post" action="" onSubmit="CheckDomain();return false;" id="frmDomainCheck">
<input class="search_domain" name="frmURL" id="frmURL" value="Please enter your domain name here..." onfocus="if(this.value == 'Please enter your domain name here...') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Please enter your domain name here...';}" type="text" />
<span id="frmGO"><input name="" value="GO!" class="search_domain_go" type="submit" /></span>
<form>
</div><!-- /# end search form -->
<div class="domain_features">
<ul>
<li><span id="DomainStatus">Type in the domain and click 'GO' to check its availability.</span></li>
</ul>
</div>
</div>
...
</body>
I used your code and then added the following for checkdomain.cfm
<cfoutput>AVAILABLE</cfoutput>
It worked just fine. In your handleResponse function, put an alert(s); statement at the top to see just what you're getting back from checkdomain.

Google AJAX Transliteration API :- How do i translate many elements in page to some language at one stretch?

I have many elements on page and all of which i want to translate to some language. The language is not the same for all fields, that is, for 1st field it may be fr and for third field it may be en then again for 7th field it may be pa.
Basically i wrote the code and it's working :-
<script type="text/javascript">
//<![CDATA[
google.load("language", "1");
window.onload = function(){
var elemPostTitles = document.getElementsByTagName("h4");
var flag = true;
for(var i = 0 ; i < elemPostTitles.length ; i++){
while(flag == false){
}
var postTitleElem = elemPostTitles[i];
var postContentElem = document.getElementById("postContent_" + i);
var postTitle = postTitleElem.innerHTML;
var postContent = postContentElem.innerHTML;
var languageCode = document.getElementById("languageCode_" + i).value;
google.language.detect(postTitle, function(result) {
if (!result.error && result.language) {
google.language.translate(postTitle, result.language, languageCode,
function(result) {
flag = true;
if (result.translation) {
postTitleElem.innerHTML = result.translation;
}
});
}
});
flag = false;
}
As you can see, what i am trying to do is restrict the loop from traversing until the result of previous ajax call is receieved. If i don't do this only the last field gets translated. My code works nicely, but because of the infinite loop, i keep getting errors from Mozilla to "stop executing scripts". How do i get rid of this? Also, is my approach correct? Or some inbuilt function is available which can ease my task? Thanks in advance :)
Why don't you call the function to check the next h4 recursively from within the detect/translate completed callbacks. Send the next recursion the next h4 using something like JQuery's next() function.
What you're doing is running the endless loop on the same thread as the outer loop.
I suggest you post a more complete question and code next time to prevent people who like to provide working answers from having to spend time guessing what you are trying to do.
Here is a working example using recursion. Unless you have thousands of items, the tail should be tolerable.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="http://www.google.com/jsapi">
</script>
<script type="text/javascript">
google.load("language", "1");
function initialize() {
var elemPostTitles = document.getElementsByTagName("h4");
var index = elemPostTitles.length - 1;
foo(index);
function foo(index) {
var postTitleElem = elemPostTitles[index];
var postTitle = postTitleElem.innerHTML;
var postContentElem = document.getElementById("postContent_" + index);
var postContent = postContentElem.innerHTML;
var languageCode = document.getElementById("languageCode_" + index).value;
google.language.detect(postTitle, function(result) {
if (!result.error && result.language) {
google.language.translate(postTitle, result.language, languageCode,
function(result) {
if (result.translation) {
postTitleElem.innerHTML = result.translation;
}
if (--index > -1) {
foo(index);
}
});
}
});
};
}
google.setOnLoadCallback(initialize);
</script>
</head>
<body>
<h4>
this is some text</h4>
<h4>
this is some text</h4>
<h4>
this is some text</h4>
<h4>
this is some text</h4>
<h4>
this is some text</h4>
<input type="text" id="languageCode_0" value="en" />
<div id="postContent_0">
</div>
<input type="text" id="languageCode_1" value="hi" />
<div id="postContent_1">
</div>
<input type="text" id="languageCode_2" value="es" />
<div id="postContent_2">
</div>
<input type="text" id="languageCode_3" value="fr" />
<div id="postContent_3">
</div>
<input type="text" id="languageCode_4" value="ar" />
<div id="postContent_4">
</div>
</body>
</html>

Resources