I have a view in which a quiz is displayed using an external js file. When the quiz is completed, I am appending some new html to the screen, including a new button that is suppose to, upon being clicked, send the user to the practiceTask function of my Main controller. However, when it is clicked I get the error:
Uncaught SyntaxError: Invalid flags supplied to RegExp constructor 'practiceTask'
Because the code is in .js file, I can't use site_url or base_url, as far as I know. Is this the correct way to do this?
Relevant JS:
$('#imageLocation').attr("src", "");
var html = '<div class="instruction_block"><p class="instruction_text" style="text-align: center; margin-top: 0">You have completed the ' + text + ' test</p><div class="button_placement" style="margin-top: 300px;"><input class="rounded" style="position: absolute; bottom: 0; right: 0; width: 250px;"" type="button" value="Continue to the next task" onClick="/main/practiceTask/3"></div>';
$('#final_message').append(html);
Main Controller function:
public function practiceTask($task_id){
$this->load->model('Main_model');
echo ($task_id);
$json_key = $this->Main_model->getKey($task_id);
$json_key = json_decode($json_key, true);
shuffle($json_key);
$data['test_key'] = $json_key;
$data['task_id'] = $task_id;
$this->load->view('practice_test_view', $data);
}
Any help would be much appreciated!
If you want to get a value into a JS page, you can put it into a hidden input and parse with JS on the page load so that it is available for you to use.
The problem you might be having is with your onclick
onClick="/main/practiceTask/3"
do this with jQuery
var html = '<div class="instruction_block"><p class="instruction_text" style="text-align: center; margin-top: 0">You have completed the ' + text + ' test</p><div class="button_placement" style="margin-top: 300px;"><input class="rounded" style="position: absolute; bottom: 0; right: 0; width: 250px;"" type="button" value="Continue to the next task" data-url="/main/practiceTask/3"></div>';
$(document).on('click', '.button_placement input', function(e){
e.preventDefault();
window.top.location = $(this).data('url');
});
This way it creates an event that will trigger whenever you click on the button. It will read the data-url value and redirect you to that page.
Good luck ;)
Related
I've created a popover that launches when you click on the specified area with the corresponding data-toggle, it's working perfectly in Chrome but in Firefox I keep getting the error:
Error: Please use show on visible elements
show, _enter, toggle, _setListeners, dispatch, handle
The error resides in the bootstrap.min.js file that is used in my project.
Now I know that it has probably something to do with adding ('show')after the .popover part, but I can't get it to work. My popover function:
// popover initialization - on click
$('[data-toggle="zero-1"]').popover({
html: true,
trigger: 'click',
placement: 'bottom',
// main function when popover fires
content: function engine() {
// execute the actions of the lawmaker() first, then the ruler()
return lawmaker(this,this,this) + ruler((($(this).data('xray'))),(($(this).data('yray'))));
// insert image and close button in popover
function lawmaker(i1,a1, b1,) {
// get the data-image str value
var mig = $(i1).data('img');
// console.log(mig);
// return the visuals and close button for the popover
return '<img src="' + mig + '" /> <button id="close-popover" data-toggle="clickover" class="btn btn-small btn-primary pull-right" onclick="$(\'.popover\').remove();">Close please!</button>';
}
}
});
.popover {
position: absolute;
transform: translate3d(258px, 63px, 0px);
top: 0px;
left: 0px;
will-change: transform;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<map>
<area class="grz" data-toggle="zero-1" data-xray="105" data-yray="70" shape="rect" coords="80,60,130,80" href="javascript://" data-img="img/zero/zero-2.png" title="Zero">
</map>
Any thoughts in solving this problem? :)
When I tried to initialize tooltip via javascript, tooltip din't work, yet there was no error. I got the same error as you've quoted in the question when I used $(element).tooltip().tooltip('show').
Here is link to possible reason why that happens https://github.com/twbs/bootstrap/issues/24918.
I ended up just putting html attributes on tooltip element to get it working
<span data-toggle="tooltip" data-placement="right" title="my tootltip content">help</span>
This question already has answers here:
Get clicked element using jQuery on event?
(6 answers)
Closed 5 years ago.
I'm not a big fan of putting my event listeners (specifically onclick in this case) in the HTML, mostly because I can't use
$(document).ready(function(){})
I would much rather define the buttons' onclick as I've commented it in the startup function. However, this doesn't refer to the clicked button when I put the listener in the script (I'm guessing because it doesn't "know" which button I clicked). I've tried setting event as a parameter to the showImage function, and finding the e.target inside it, but this didn't work either. Is there a way I can refer to the clicked button without having the onclick inside the HTML tag?
//$(document).ready(function() {
window.onload = startup;
function startup() {
$("img").hide();
//$("button").click(showImage(this));
}
function showImage(e) {
var chosen = e.value;
$('#' + chosen).fadeIn(500);
$('img:not(#' + chosen + ')').hide();
}
//});
body {background-color: #EFEFEF;}
#content {width: 80%; margin: auto; background-color: white; padding: 15px; font-family: "Century Gothic",sans-serif;}
img {height: 250px; border: solid 1px black;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<img id="pig" src="http://www.igjerstad.no/sites/default/files/styles/nodeimage/public/field/image/gris-750-5.jpg?itok=TJa-iUVg">
<img id="cow" src="https://www.matmerk.no/cms/images/3675/1200/1200/ku-nyt-norge.jpeg">
<img id="sheep" src="https://media.timeout.com/images/103778879/630/472/image.jpg">
<img id="hen" src="http://africahitz.com/wp-content/uploads/2017/01/hen-white-and-black-color.jpg">
<br>
<button value="pig" onclick="showImage(this)">Gris</button>
<button value="cow" onclick="showImage(this)">Ku</button>
<button value="sheep" onclick="showImage(this)">Sau</button>
<button value="hen" onclick="showImage(this)">Høne</button>
Thanks in advance!
PS. I would guess someone else has had this problem and maybe asked about it here. I did check if I could find a similar question on the site, but found nothing. However, I have failed to find that before, so I'm sorry if this is a duplicate.
PS2. The images in my code are not mine, nor do I have the rights for them. Please don't sue me ':D
PS3(!!). I'm not an experienced programmer, my terminology might be wrong some places. Feel free to correct me :)
Firstly you need to define function() in a click function so it should look like this:
$("button").click(function() {
//code to execute here
});
Instead of this:
$("button").click(//code to execute here);
When calling this in a button it will refer to the button and if I understand your code right, the image is hidden therefore if that is the button then you can't click a hidden image, if you're using a separate button to hide the image then in the click function you need to have e stated as the image element.
To use this you also need to call it as $(this) not just this.
This should work.
//$(document).ready(function() {
window.onload = startup();
function startup() {
console.log("window loaded");
$("img").hide();
$("button").click(function() {showImage(this)});
}
function showImage(e) {
console.log("onside eras");
var chosen = e.value;
$('#' + chosen).fadeIn(500);
$('img:not(#' + chosen + ')').hide();
}
//});
this will be set inside the event handler as event.currentTarget Ref. If you are using jQuery you can make a jQuery object from it by doing $(this). So to get the value you can do:
var chosen = $(this).prop('value');
I have also added a class myclass to the buttons to select it using $('.myclass') so that this can be seperated from other possible buttons in the page. You can also do $('button') instead to select all buttons irrespective of the class.
UPDATE
Just saw your commented out code:
$("button").click(showImage(this)); // When a button is clicked
// call the function returned by showImage(this).. err it doesnt return
// a function so it fails.
you should pass a function reference or simply a function name to the click event registration. like .click(showImage) without any function call (). In your code it will execute showImage(this) and bind the returned value to the event listener, which will apparently fail.
It should actually be:
$("button").click(showImage); // when a button is clicked
// call the function showImage with this=<clicked button> and param=event
and this will be automatically set inside the function as event.currentTarget
$(document).ready(function() {
window.onload = startup;
function startup() {
$("img").hide();
//$("button").click(showImage(this));
}
function showImage(e) {
var chosen = $(this).prop('value');
$('#' + chosen).fadeIn(500);
$('img:not(#' + chosen + ')').hide();
}
$('.myclass').on('click', showImage);
});
body {background-color: #EFEFEF;}
#content {width: 80%; margin: auto; background-color: white; padding: 15px; font-family: "Century Gothic",sans-serif;}
img {height: 250px; border: solid 1px black;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<img id="pig" src="http://www.igjerstad.no/sites/default/files/styles/nodeimage/public/field/image/gris-750-5.jpg?itok=TJa-iUVg">
<img id="cow" src="https://www.matmerk.no/cms/images/3675/1200/1200/ku-nyt-norge.jpeg">
<img id="sheep" src="https://media.timeout.com/images/103778879/630/472/image.jpg">
<img id="hen" src="http://africahitz.com/wp-content/uploads/2017/01/hen-white-and-black-color.jpg">
<br>
<button value="pig" class="myclass">Gris</button>
<button value="cow" class="myclass">Ku</button>
<button value="sheep" class="myclass">Sau</button>
<button value="hen" class="myclass">Høne</button>
I am trying to complete the random quote generator on FreeCodeCamp. I pretty much have it but i decided i wanted to go one step further and change the background image with the button as well. I believe the background img is being cached from the very first call where the background img is originally set. Therefor every time i click the button the browser is essentially reloading the cached img instead of revisiting the site and pulling a new img.
The source i am using is just a site that returns a different image every visit.
I have tried adding a time stamp to the end of the url and the site just throws a invalid address image at me.
<html>
<head>
</head>
<body>
<div class="container-fluid" id="mainDiv">
<div class = "row text-center">
<div class = "col-xs-12 well" id = "quote">
The quote will go here
</div>
</div>
<div class = "row text-center">
<div class = "col-xs-12">
<button id = "getQuote" class = "btn btn-primary">
Get Quote
</button>
</div>
</div>
</div>
</body>
</html>
body{
background-image: ;
}
#mainDiv{
margin: 0 auto;
max-width: 400px;
margin-top: 200px;
}
$(document).ready(function(){
$('body').css('background-image', 'url("https://source.unsplash.com/random")');
$.getJSON("http://quotes.stormconsultancy.co.uk/random.json", function(json){
$("#quote").html('"' +json.quote + '"<br> - ' + json.author);
});
$("#getQuote").on("click", function(){
$('body').css('background-image', 'url("https://source.unsplash.com/random")');
$.getJSON("http://quotes.stormconsultancy.co.uk/random.json", function(json){
$("#quote").html('"' +json.quote + '"<br> - ' + json.author);
});
});
});
Timestamp won't work because it is a 302 redirect, and the client-side script cannot intercept the 302 redirect, it is resolved automatically and you cannot do anything about that. You can read 302 headers on the server side though. You can try getting the image in your server, have it resolve the 302 and respond with the correct url.
If you are using the API you can try using ajax:
$.ajax({
url: "https://api.unsplash.com/photos/random?client_id=32d223323",
cache: false,
success: function(result){
$('body').css('background-image', 'url("' + result.urls.full + '")');
}
});
I have a problem with my web application. I've created a tchat in Ajax and I want it to be loaded when I click on a button. It works, but the dynamic data loaded doesn't support jQuery.
When I click on the button, I dynamically change the content of a div, initially empty. But on this finder (which open) I have a link which should load smileys simply in changing the height of the div, which is initially at 0 px.
I've done tests, and when I click on the button, the height is good changed, but nothing appear on the screen.
Here is a screenshot of my chat:
When I click on the smiley, I should see that:
But nothing happened.
Here is the code that works fine because the height is changed (I've tested it) :
var elm = window.document.getElementById('myCGU_Appear-1');
if (elm.style.height == "0px") {
elm.style.height = "100px";
elm.style.overflow = "auto";
window.document.getElementById('appear_emoticon-1').src = "/assets/images/emoticons/my_small_emoticons_000.png";
} else {
elm.style.height = "0px";
window.document.getElementById('appear_emoticon-1').src = "/assets/images/emoticons/my_small_emoticons_01.png";
}
I think I've done a mistake somewhere because yesterday the code worked fine...
Here is the code that load the tchat :
$.ajax({
url:"/scripts/ajax/load_tchat.php",
type: "POST",
data: "method_call=open",
dataType: "json",
success: function(data){
console.log(data);
if(data.tchat_operation == 'open') {
// load datas
$("#frameChat").html(data.tchat_content);
// open the tchat
frameChat.classList.remove("Espace-Chat-Ferme");
frameChat.classList.add("Espace-Chat");
}
},
error: function(resultat, statut, erreur){
console.log(resultat);
console.log(erreur);
}
});
And here is the JSON code that is send to me and that I've on my div :
> this.tchat_content
< "
[...]
<div style=\"position: absolute; bottom: 5px; width:280px; class=\"myBackgroundGreyLight\">
<div class=\"section group\">
<div class=\"col span_1_of_1\"><div id=\"myCGU_Appear-1\" name=\"myCGU_Appear-1\" style=\"height:0px;margin-bottom:2%;-webkit-transition:all 0.2s ease-in;transition: 0.5s ease-in-out;overflow: hidden;display:block;\" class=\"myBackgroundGreyLight\">All emoticons</div>
<a href=\"#\" onclick=\"My_CGU_Appear2(-1,5000)\" class= \"button scrolly\" >
<img id=\"appear_emoticon-1\" src=\"/assets/images/emoticons/my_small_emoticons_01.png\" width=\"6%\">
</a><div class=\"fileUpload\">
<input type=\"file\" accept=\"image/x-png, image/gif, image/jpeg, image/jpg\" id=\"imgInp-1\" />
</div>
<div>
<a href=\"#ouvre_photo\" onclick=\"AddImageInInput2(this,-1);\">
<img id=\"blah-1\" src=\"\" alt=\"\" />
</a>
</div><div contentEditable=\"true\" class=\"contact_message\" id=\"txt_comments-1\" onkeyup=\"ia_content_analysis(-1, event,2);\" style=\"background-color:white;max-height:125px;overflow-y:auto;overflow-x:hidden;min-height: 50px;\"></div>
<div id=\"test-1\" style=\"float:right;\">
<h4> </h4>
</div>
<div id=\"callback_-1\" style=\"font-size:11px;margin-top:10px;\"></div>
<div style=\"clear:both; display:block; height:10px;\"></div>
<div style=\"display:inline-block;width:100%;\">
<a style=\"display:inline-block;background-color:#bf0e07;float:right;border-radius:4px;padding:5px;cursor:pointer;width:50px;text-align:center;font-size:12px;color:white;\" rel=\"-1\" class=\"publish_message\">Publier</a>
</div>
</div>
</div>
</div>
<script src=\"/assets/javascript/jquery.min.js\"></script>
<script src=\"/assets/javascript/My_JSFunctions.js\"></script>
<script src=\"/assets/javascript/ajax.js\"></script>"
Thanks if you can help me or show me the right way :)
You haven't set any event handler on your emoticon-button. After loading HTML data via ajax you have to reinitialize all your event handlers previously set on your elements if you had set them via ID. So instead of reinitializing all the time you could try:
$(document).on('click', '#yourButtonId', function() { /* my logic */ });
instead of assigning the event handler directly on the dynamic content. I hope I got you right. Else providing a JSFiddle would help.
I am trying to replace the content of a div with an iframe that allows the user to input a URL to display another page. I will, ideally, add another button next to the Change URL button that links to a specific page.
However, I cannot get this code to work. I can get the div to be replaced with text and some html. But the iframe code won't load when I put this in. I am suspecting it's due to the quotation marks.
I am a bit of a novice at javascript/JQuery so any help with this will be greatly appreciated.
Here is what I have going for the code below.
<style>
#target {
width: 200px;
height: 340px;
}
</style>
<script>
$(function load($){
var $iframe = $('#target'),
$change = $('#change'),
$url = $('#url');
$change.click(function url() {
$iframe.attr('src', $url.val());
});
});
document.getElementById("c_emot").innerHTML = "<iframe id="target" src="/"></iframe><br>
<input id="url" type="text"><br>
<button id="change" type="button">Change URL</button>";
</script>
Your quoted string is all wrong. Try this:
document.getElementById("c_emot").innerHTML = '<iframe id="target" src="/"></iframe><br>
<input id="url" type="text"><br><button id="change" type="button">Change URL</button>';
for reference: http://www.javascripter.net/faq/quotesin.htm
Also, your click event is not being bound to the button after the button is created. You can make it persistent on the button's container like this:
$('#c_emot').on('click', '#change', (function(){
$('#target').attr('src', $('#url').val());
});
And if youre going to mess with the DOM, you have to be sure that the element you want to manipulate has already been created when your code is run:
$(document).ready(function(){
// put all your code here
});
but maybe you should be creating elements instead of dumping markup into the container:
document.onreadystatechange = function () {
if(document.readyState == "complete") {
var container = document.getElementById("c_emot");
var iframe = document.createElement('iframe');
iframe.src = "/";
container.appendChild(iframe);
var input = document.createElement('input');
input.id = "url";
input.type = "text";
container.appendChild(input);
var button = document.createElement('button');
button.id = "change";
button.innerHTML = "Change URL";
button.addEventListener('click', function() {
iframe.src = input.value;
});
container.appendChild(button);
}
}
Not sure if that event listener will work, got to try it and see :)
Have you tried just doing it without messing around with the DOM?...
<iframe name="urlbox"></iframe>
<input type="text" id="urlinput" />
<button onclick="window.open(document.getElementById('urlinput').value, 'urlbox')">Navigate!</button>
Most browsers wont let you navigate the iframe to a different domain for security anyway, so maybe this is all for nothing.
This demo has 2 features:
Using the text input, user can enter a URL to change the src of the iframe.*
This is possible by using this function:
function changeSrc(src) {
var iframe = document.getElementById('site');
site.src = src;
}
*Be aware that not all sites are iframe friendly, so expect some sites that my function will simply not work for.
Notice the links to various sites. Their behavior has been alter--rather than jumping to the site, it opens the site within the iframe.
Each link is a normally constructed anchor element <a> with one exception. It's value for their attribute target is site.
site is the name of the iframe. When an anchor has target="name of iframe"` the anchor opens the site within that targeted iframe.
This must be the iframe's name attribute not the iframe's id.
Snippet
function changeSrc(src) {
var iframe = document.getElementById('site');
site.src = src;
}
body {
width: 100vw;
height: 100vh;
overflow: hidden;
}
section {
height: 100%;
width: 100%;
overflow-y: auto;
}
<form id="form" onchange="changeSrc(url.value);">
<fieldset>
<legend>Enter URL</legend>
<input id="url">
<input type="submit" />
</fieldset>
</form>
ROOT Example W3Scools jsFiddle
jsDelvir JavaScript Tut Plain JS
<section>
<iframe id="site" name="site" src="/" width="100%" height="100%" frameborder="0"></iframe>
</section>