I am using WordPress and I am trying to get and assign the value of a data attribute to a variable using JavaScript inside functions.php in my custom child theme.
The page renders the following body:
<body class="(...)" data-elementor-device-mode="desktop">
I have the following function:
var body = document.body;
console.log(body);
var bodyDevice = body.dataset.elementorDeviceMode;
console.log(bodyDevice);
The first console.log returns the body as expected, but the second console.log still returns "undefined".
It must be a syntax issue, since the following
var bodyDevice = body.clientWidth;
console.log(bodyDevice);
will return the current width of the body element (which solves my issue); anyway, why is
var bodyDevice = body.dataset.elementorDeviceMode;
console.log(bodyDevice);
not returning "desktop" value?
Elementor inserts the data set by JavaScript on its initialization, see line 271 : https://github.com/elementor/elementor/blob/master/assets/dev/js/frontend/frontend.js
Basically your code is returning nothing because it is executed before the Elementor has inserted the data set... So, there is no data-elementor-device-mode at the moment your code is executed.
Try to execute your code after the page loads using like:
window.onload = function() {
var bodyDevice = document.body.dataset.elementorDeviceMode;
console.log(bodyDevice);
};
Related
I just want to be able to access variable userid in document.ready function. It's accessible in the JSP page but not in jQuery. I am able to print value of ${userid} on the same JSP page but not in jQuery. I have passed userid obj with model and view object to this JSP page. However I am not able to access that object.
$(document).ready(function(){
var examid = ${userid};
alert("Hello !");
//alert(username);
});
If the value of ${userid} is a string then you need to wrap it in quotes, otherwise you'll be getting a syntax error thrown in your JS code.
For example var examid = '${userid}';
– Rory McCrossan Apr 4 at 10:45
How do I get reference of the <div> id and title from a external JS by using the code below:
function recordedEvent() {
var v_Id = $(this).attr('Id');
var v_Title = $(this).attr('Title');
var o = { Title : v_Title, ObjectId : v_Id };
alert(JSON.stringify(o));
}
The function is called in the HTML with a onclick called box1().
Code in CplTemplateSetup.js is where I want to run the function from into the HTML:
content_left_30_four_click_images_right_70_head_content_template.html
Any help would be appreciated.
P.S.: JSON data (zip archive)
Well the most obvious problem is that you don't have a closing parenthesis after your callback.. otherwise the code looks good
Edit
window.lastClickedBoxData = {}; // just reassign that within your function
or
window.runThisWhenClicked = function () {
var v_Id = $(this).attr('Id');
var v_Title = $(this).attr('Title');
var o = { Title : v_Title, ObjectId : v_Id };
};
then just
$(".box").click(window.runThisWhenClicked);
I don't think that the problem that you're facing would be apparent to anyone who doesn't view your code.
You defined a function within a script tag, in the html, and called that function in the onclick attribute of the box being clicked on. To that function, this refers to the box that was clicked on. From there, you call a function within an external js document. In that function, this refers to the window object. In other words, for the code that you posted, $(this) is a jquery instance of the window object which doesn't have the attributes that you're looking for, such as id and title, so they're blank.
To see what I'm talking about open the console and add the following line of code to each of your functions:
console.log(this);
If you're having trouble doing that, the following code should work as well, but it's not as good for debugging:
alert(this);
You need all of your code to be in the html script tag or in the external document. Also, you shouldn't define the function to be called during a click event using onclick within the html. It's better to do it using javascript or jquery so that your javascript is completely separate from your html.
EDIT: You shouldn't update your question with an answer. You should edit the original question with this information so that anyone having a similar problem can find the solution. I'd have commented on the answer directly, but I don't have the reputation to do this.
I have a javascript function and when it is called I want to insert a partial into a div. All is working fine, but, when I want to pass some javascript into Html.Partial ViewDataDictionary, it isn't passing the rendered javascript.
<script>
function addExperience() {
#{var uid = #MvcHtmlString.Create("new Date().getTime()");}
console.info(#uid); //output ok !
var partialView = #(Html.Raw(JsonConvert.SerializeObject(Html.Partial("~/Views/Dashboard/_editUserExperience.cshtml", Model, new ViewDataDictionary { { "id", uid } }).ToString().Trim('"'))))
$("#newExperienceSection").append(partialView); //it renders "new Date().getTime(), not the number
}
</script>
Thank you !
If you call Jsonconvert.SerializeObject with a string (Html.Partial returns a string), it returns a string.
So you statement
var partialView = ... will be rendered as
var partialView = "the contents of the partial view";
That's why, when you do this:
$("#newExperienceSection").append(partialView);
it actually displays the javascript as text.
If you want to get a partial view to execute javascript, you can return javascript inside script tags, and as soon as you add that to the DOM it gets executed, for example if you set your _editUserExperience.cshtml as this:
<script>
alert('this gets executed as soon as you do add this to the DOM with the jQuery append command');
</script>
When you execute $("#newExperienceSection").append(partialView); you'll see the alert.
An easier way to insert a partial view is to take advantage of $.ajax, for example, in addExperience:
$.get('#Url.Action("ActionMethodThatReturnsPartial", "YourController")').done(function(theHtmlReturned) {
$("#newExperienceSection").html(theHtmlReturned);
});
($.get is just shorthand for $.ajax using a get request)
Source: http://api.jquery.com/jquery.ajax/
http://api.jquery.com/jquery.get/
http://api.jquery.com/category/deferred-object/
I am trying to pass 4 variables from one js file to another.
I read here that you must write:
window.myVar = "foo";
to make your variable "super"-global.
In the first js file, I have
window.signJoueur1 = string1.charAt(7);
window.signJoueur2 = string2.charAt(7);
window.valeurJoueur1 = random1;
window.valeurJoueur2 = random2;
In the second js file, I did
console.log(window.signJoueur1);
console.log(window.signJoueur2);
console.log(window.valeurJoueur1);
console.log(window.valeurJoueur2);
function trouveCombinaison(signJoueur1, signJoueur2, valeurJoueur1, valeurJoueur2)
{
console.log(signJoueur1);
console.log(signJoueur2);
console.log(valeurJoueur1);
console.log(valeurJoueur2);
}
It should work, but all console.log return `undefined'.
If you want more informations here are the full codes:
first .js http://pastebin.com/0zJKFNem
second .js http://pastebin.com/TsWc7TxL
the html http://pastebin.com/t3SzwZSC
So, my question is, how can I actually pass through the variables?
You are trying to use the values before they exist.
The code that assigns the values to the variables are inside a function, and that function isn't called until you click a button. The code that tries to show the values is executed when the page loads, so it uses the variables before they have been assigned any values.
Actually i just had to put window. in the second console.log group.
Such as :
function trouveCombinaison()
{
console.log(window.signJoueur1);
console.log(window.signJoueur2);
console.log(window.valeurJoueur1);
console.log(window.valeurJoueur2);
}
The fact that the console.log out of the function don't work is that it's executed when the page loads, as explained by #Guffa.
Now it works.
My form calculations work in my jsfiddle, however in my wordpress page, it says Uncaught TypeError: Cannot set property 'onchange' of null. Is my page not loading the function when it loads?
(javascript in the header)
function doTotal(form) {
var a = (+form.halfday1.value);
var b = (+form.fullday1.value);
form.total1.value = a + b ;
}
document.getElementById("quote").onchange = function (){doTotal(this)};
http://jsfiddle.net/2666c/
Your code not run, becouse on moment it try to find the <element id="quote"/> there are no such elements. You need to put your code under this element. Or run it on document load event.
As example:
jQuery(document).ready(function($){
jQuery('#quote').change(function (){doTotal(this)});
});